Defer CSS Loading with loadCSS


Asynchronously load non-critical CSS files with loadCSS to avoid blocking page rendering.





TLDR : If you have already segregated your CSS into critical and non-critical CSS (for above-the-fold page display), and all you seek is the code snippet to defer loading of non-critical CSS, head over here.


To defer loading of non-critical CSS, perform the following steps:


Identify critical and non-critical CSS

Here are various critical CSS generators - pick the one that fits your requirement:


Inline critical CSS and preload non-critical CSS

Inline the identified critical CSS. Rest of the CSS (non-critical) needs to be preloaded without the rel='stylesheet' attribute. This is because the 'stylesheet' value causes the browser to block rendering while the file is being downloaded.


<!-- Standard CSS Loading -->
<link type="text/css" rel="stylesheet" href="[yourcssfile]" />

<!-- Deferred loading non-critical CSS -->
<link rel="preload" href="[yourcssfile]" as="style" onload="this.onload=null; this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="[yourcssfile]" ></noscript>

Reliably preload across browsers with loadCSS

One issue with preloading is that it is not supported by browsers like Firefox and Internet Explorer (as of Nov 2018). As a result, these browsers will not download the CSS file and this can result into serious display issues for your web-pages. This makes it critical to include a JavaScript polyfill for preload - loadCSS.



<style>
[Your critical CSS goes here]
</style>

<!-- Reliably defer loading of non-critical CSS with loadCSS-->
<link rel="preload" href="[yourcssfile]" as="style" onload="this.onload=null; this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="[yourcssfile]" ></noscript>

<!-- Inline the loadCSS preload polyfill code or load it via external JS file-->
<script src="./cssrelpreload.js"></script>

Above implementation ensures that non-critical CSS is reliably loaded without blocking page render while in-lined CSS adequately displays above-the-fold page.






Looking to improve your website's speed? Let Tezify team take care of your website's performance intricacies.