I am trying to optimize the CSS delivery following the google documentation for developers https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example
As you can see in the example of inlining a small CSS file the critical CSS in inlined in the head and the original small.css is loaded after onload of the page.
<html> <head> <style> .blue{color:blue;} </style> </head> <body> <div class="blue"> Hello, world! </div> </body> </html> <noscript><link rel="stylesheet" href="small.css"></noscript>
My question regarding this example:
How to load a large css file after onload of the page?
The most common solution, to defer the loading of your render blocking CSS, and reduce render-blocking round trips is called loadCSS by Filament Group. The latest version takes advantage of the not yet fully supported rel='preload' attribute that allows for asynchronous loading of CSS.
When it comes to page speed, defer loading CSS scripts is most beneficial when your web pages load large CSS scripts. Now, you can't just stick all your CSS in one file, defer load it, and expect your web pages to turn out well.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
If you don't mind using jQuery, here is a simple code snippet to help you out. (Otherwise comment and I'll write a pure-js example
function loadStyleSheet(src) { if (document.createStyleSheet){ document.createStyleSheet(src); } else { $("head").append($("<link rel='stylesheet' href='"+src+" />")); } };
Just call this in your $(document).ready()
or window.onload
function and you're good to go.
For #2, why don't you try it out? Disable Javascript in your browser and see!
By the way, it's amazing how far a simple google search can get you; for the query "post load css"
, this was the fourth hit... http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery
A little modification to the function provided by Fred to make it more efficient and free of jQuery. I am using this function in production for my websites
// to defer the loading of stylesheets // just add it right before the </body> tag // and before any javaScript file inclusion (for performance) function loadStyleSheet(src){ if (document.createStyleSheet) document.createStyleSheet(src); else { var stylesheet = document.createElement('link'); stylesheet.href = src; stylesheet.rel = 'stylesheet'; stylesheet.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(stylesheet); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With