Load stylesheets in background to increase page speed


Andres Canavesi
Aug 16, 2020
Optimize the page loading time by loading your style sheets in background.
featured image

With only two simple steps your pages will load faster, and the most important: using only native JavaScript

The trick will be to use a default tag in rel attribute and modify it once the page loads

Step 1

Include your stylesheets this way

      
<link id="stylesCss" as="style" rel="preload" href='/stylesheets/style.css' />
      
    

Step 2

After the page loads call this piece of code:
      
document.getElementById('stylesCss').rel='stylesheet'
      
    

So the whole code will be

      
<script type="text/javascript">
   document.addEventListener("DOMContentLoaded", function(event) { 
      // load css styles after the page loaded
      document.getElementById('stylesCss').rel='stylesheet'
   });
</script>
    
    
After the page loads the tag will be this:
      
<link id="stylesCss" as="style" rel="stylesheet" href='/stylesheets/style.css' />
      
    

And that's it. The browser will listen to this action and will load the stylesheets properly. Now your page will load a bit more faster

Of course, you can do this for any other style you have