How to load css async properly?

As a test to learn more about website optimization, I tried to get my site to get the perfect result on the PageSpeed ​​Insights page. Everything is going great so far, except for the CSS delivery.

I was able to get the perfect result using the preload tag, but for some reason, that didn't load for Firefox. So I tried other solutions.

Then I switched to this:

<link rel="stylesheet" href="~/css/site.min.css" media="none" onload="if(media !== 'all')media='all';">
<noscript><link rel="stylesheet" href="~/css/site.min.css"></noscript>

      

Which seemed very effective, but pagespeed doesn't pick it up, so it only gives me 85 points.

The same thing happened when I used <link rel="stylesheet" href="~/css/site.min.css" media="none"/>

in the head and <link rel="stylesheet" href="~/css/site.min.css">

at the end of my body.

Then I tried loading my css using Javascript like this:

<noscript id="deferred-styles">
    <link rel="stylesheet" href="~/css/site.min.css"/>
</noscript>
<script>
    var loadDeferredStyles = function() {
        var addStylesNode = document.getElementById("deferred-styles");
        var replacement = document.createElement("div");
        replacement.innerHTML = addStylesNode.textContent;
        document.body.appendChild(replacement);
        addStylesNode.parentElement.removeChild(addStylesNode);
    };

    var raf = requestAnimationFrame ||
        mozRequestAnimationFrame ||
        webkitRequestAnimationFrame ||
        msRequestAnimationFrame;
    if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
    else window.addEventListener('load', loadDeferredStyles);
</script>

      

But it also had the same effect! Pagespeed didn't pick it up and gave me a bad rating. Why, why? Because the above code can be found on their website!

+3


source to share


2 answers


according to my experience with google pagepeed, to optimize css delivery, you need to write inline css code of the first fold of your web page. So this can be colored quickly and the rest of the css can be written in an external file. Minify and execute css files used on the page. See this link for more information optimize css delivery



+1


source


This is what I use immediately before </body>

and works great.



	<script type="text/javascript">

	function downloadAtOnload() {
	// Dynamically load CSS
	var ls = document.createElement("link");
 	ls.rel="stylesheet";
 	ls.href= "css/my-css-file.css";
 	document.getElementsByTagName("head")[0].appendChild(ls);

	}
	if (window.addEventListener) window.addEventListener("load", downloadAtOnload, false);
	else if (window.attachEvent) window.attachEvent("onload", downloadAtOnload);
	else window.onload = downloadAtOnload;
	</script>
      

Run codeHide result


-1


source







All Articles