TJB
TJB

Reputation: 3836

Load CSS only when template is completely done rendering

I had a link to boostrap stylesheet cdn that was causing some render blocking issues which was performing my site performance according to Google Page Speed Insights. I solved this by only taking the required above the fold bootstrap css and putting it in a 'critic_bootstrap.css' file. When the page is completely rendered, I do want to load that bootstrap CDN anyway for all the other styles that are not above the fold. How can I accomplish this ? I tried appending it to the head of my document in a jquery document.ready function, but it seemed to still cause PSI render blocking issues like it was till being loaded before the page was being rendered.

Upvotes: 0

Views: 844

Answers (3)

indarCode
indarCode

Reputation: 90

Try to load the css at $(window).load() instead of $(document).ready().

for an instance:

  $(window).load(function() {
          $('head').append('<link rel="stylesheet" href="common.css" type="text/css" />');
    });

Upvotes: 1

Kannan K
Kannan K

Reputation: 4461

Try this:

$(document).ready(function(){
   $('head').append('<link rel="stylesheet" type="text/css" href="bootstrap.css">');
}

Upvotes: 1

tao
tao

Reputation: 90013

Use

<link rel="preload" href="mystyles.css" as="style" onload="this.rel='stylesheet'">

On top of this, if you want to disable FOUC for good, add

body {
  overflow:hidden;
}

to your above the fold CSS and override it in your async CSS with

body {
  overflow:auto;
}

The above is just a summary. If you're interested here's a full post about the method: Modern Asynchronous CSS Loading, also containing a polyfill for non-supporting browsers.

This may not look like a big improvement over other approaches, but one advantage that rel="preload" brings is that supporting browsers will start downloading the file earlier than they would with say, a stylesheet with a non-matching media value.

Also read Preloading content. Support for rel="preload" is limited to Chrome, Opera and Safari but more will follow (notably Firefox v59). Also, where it's not supported it doesn't mean it doesn't work. It only means there's no improvement over using a non-existent rel type.

Upvotes: 1

Related Questions