If you seriously want to speed up your website and it loads large CSS script(s) you can’t escape defer loading certain parts of these scripts to optimize CSS delivery. Defer loading a CSS script, also often called lazy or asynchronously loading CSS, means you load certain CSS scripts after the more important parts of your website are already finished loading. These important parts are determined by your critical rendering path.
Do not lazy load small or medium sized CSS scripts
If your website uses small to medium sized CSS files you shouldn’t worry too much about defer loading the script. You’ll benefit more, in the page speed sense, by inlining all your CSS instead.
Only lazy load bigger CSS scripts
When it comes to page speed, defer loading CSS scripts is most beneficial when your website uses a large CSS script. Now you can’t just stick all your CSS in one file, lazy load it, and expect your pages to turn out well. The first view your visitors (especially ones with slow internet connections) may get of your website may look horrible because your pages will not be styled, simply because the CSS hasn’t been loaded yet. This is the reason lazy loading all your CSS is not an option. The solution to this is finding out which part of your CSS is used for the above-the-fold initial view of your page. Once you know this you should inline this CSS in your HTML header and lazy load the rest of your CSS.
How to lazy load CSS using javascript
There are a couple of methods for deferring web files. Two of the most popularly used are script Async and script Defer. However, these methods are not the best methods. Google’s PageSpeed team has come up with a great Javascript which you should use for defer loading your CSS scripts:
code :
<script type="text/javascript">
var cb = function() {
var l = document.createElement('link');
l.rel = 'stylesheet';
l.href = 'style.css';
var h = document.getElementsByTagName('head')[0];
h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
Copy and paste this script into your HTML header and replace style.css with your CSS file. The great thing about this script is that unlike many other CSS defer loading scripts it doesn’t make use of the Jquery library. It’s perfectly suited for optimizing page speed.