twan
twan

Reputation: 2659

How to defer load css files (for google speed insights)

I am trying to get a 100/100 score on Google Page Speed Insights. But it keeps telling me some css files are blocking content above the fold. How can I make sure those files are loaded after the main content is loaded? So that it doesn't show up anymore in Page Speed Insights.

I tried loading the files asynchronously using jquery, but this way the message still pops up at the page speed tool.

I tried the following:

<script>
var loadMultipleCss = function(){
    //load local stylesheet
    loadCss('myawesomestyle.css');

    //load Bootstrap from CDN
    loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css');

    //load Bootstrap theme from CDN
    loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css');
}

var loadCss = function(cssPath){
    var cssLink = document.createElement('link');
    cssLink.rel = 'stylesheet';
    cssLink.href = cssPath;
    var head = document.getElementsByTagName('head')[0];
    head.parentNode.insertBefore(cssLink, head);
};

//call function on window load
window.addEventListener('load', loadMultipleCss);
</script>

With my own file paths ofcourse.

But for Google PageSpeed Insights this didn't work.

Upvotes: 6

Views: 8745

Answers (2)

Gustavo Falc&#227;o
Gustavo Falc&#227;o

Reputation: 9

You can use ajax / jQuery to load the CSS after the page loads. That will allow you to load not important CSS whenever you want, for instance, using a setTimeout.

Example:

document.addEventListener('DOMContentLoaded', () => {
    setTimeout($('head').append("<'link rel="stylesheet" href="your_css_file.css" type="text/css" />"), 3000); 
});

Edit: Please do remove the ' character before the link word ('link). It was inserted there so stackoverflow could show the code. Otherwise it would have shown "...apend("<>"...).

In the example above the CSS will only be loaded 3 seconds after the page is fully loaded.

I did that in some of my pages, and got the 100% on pagespeed without affecting user interface or layout, as the CSS files that I do use in that method are secondary oned, like sweetalert.

Upvotes: -2

Alexander Feiglstorfer
Alexander Feiglstorfer

Reputation: 311

Can you share the link of the website you are optimizing?

Are you sure that your page is not cached somewhere?

There are two methods that worked for me:

A) You could just put the stylesheet tags after the closing </html> tag.

B) Another technique is to put following link tag into the head section:

<link rel="preload" id="stylesheet" href="/assets/css/below.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/assets/css/below.css"></noscript>

The drawback with method B is that not all browsers support rel=preload in the link tag and you will need to include the following polyfill:

<script>
/*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
!function(a){"use strict";var b=function(b,c,d){function e(a){return h.body?a():void setTimeout(function(){e(a)})}function f(){i.addEventListener&&i.removeEventListener("load",f),i.media=d||"all"}var g,h=a.document,i=h.createElement("link");if(c)g=c;else{var j=(h.body||h.getElementsByTagName("head")[0]).childNodes;g=j[j.length-1]}var k=h.styleSheets;i.rel="stylesheet",i.href=b,i.media="only x",e(function(){g.parentNode.insertBefore(i,c?g:g.nextSibling)});var l=function(a){for(var b=i.href,c=k.length;c--;)if(k[c].href===b)return a();setTimeout(function(){l(a)})};return i.addEventListener&&i.addEventListener("load",f),i.onloadcssdefined=l,l(f),i};"undefined"!=typeof exports?exports.loadCSS=b:a.loadCSS=b}("undefined"!=typeof global?global:this);

/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
!function(a){if(a.loadCSS){var b=loadCSS.relpreload={};if(b.support=function(){try{return a.document.createElement("link").relList.supports("preload")}catch(b){return!1}},b.poly=function(){for(var b=a.document.getElementsByTagName("link"),c=0;c<b.length;c++){var d=b[c];"preload"===d.rel&&"style"===d.getAttribute("as")&&(a.loadCSS(d.href,d,d.getAttribute("media")),d.rel=null)}},!b.support()){b.poly();var c=a.setInterval(b.poly,300);a.addEventListener&&a.addEventListener("load",function(){b.poly(),a.clearInterval(c)}),a.attachEvent&&a.attachEvent("onload",function(){a.clearInterval(c)})}}}(this);
</script>

I wrote an article about optimizing a page from pagespeed 59 to 100 and you can see the before and after on following branches:

Before: https://github.com/storyblok/storyblok-express-boilerplate/blob/unoptimized/views/layouts/main.hbs

After: https://github.com/storyblok/storyblok-express-boilerplate/blob/master/views/layouts/main.hbs

Upvotes: 11

Related Questions