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
The above is the detailed content of How Can You Load a Large CSS File After the Page Has Loaded?. For more information, please follow other related articles on the PHP Chinese website!