"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Load a Large CSS File After the Page Has Loaded?

How Can You Load a Large CSS File After the Page Has Loaded?

Published on 2024-11-09
Browse:387

How Can You Load a Large CSS File After the Page Has Loaded?

Optimizing CSS Delivery: Understanding the Technique of Deferred CSS Loading

To improve website performance, developers often optimize CSS delivery. One strategy mentioned in the Google Developers documentation involves inlining critical CSS in the

section while deferring the loading of the original CSS file until after the page has loaded. This approach optimizes rendering by prioritizing the display of essential styling initially.

However, this leaves us with the question: how can we load a large CSS file after the page has loaded?

Solution: Deferring the Loading of Large CSS Files

To defer the loading of a large CSS file, we can utilize a simple jQuery code snippet:

    function loadStyleSheet(src) {
    if (document.createStyleSheet){
        document.createStyleSheet(src);
    }
    else {
        $("head").append($("<link rel='stylesheet' href='" src " />"));
    }
};

By calling this function within the $(document).ready() or window.onload function, we can dynamically load the CSS file after the page has finished loading.

Method Verification

To verify that this method works, try disabling JavaScript in your browser and then reloading the page. If the page still loads correctly with the stylesheets applied, it demonstrates the successful deferral of CSS loading.

Alternative Methods

There are alternative methods to defer CSS loading, such as using the

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3