How to preload your CSS and why you should

laptop with code to preload css

So you’re trying to make your website load quicker, and you’ve done everything you know to quicken the page load time. But there are still some problems and you keep getting an issue with render blocking when you run the page through Google Page Speed tools.

What can you do to make things load quicker?

The answer is to preload external resources like CSS and JavaScript. It’s a relatively knew thing on the web and it will help speed up your website. So here’s why you should use it and how it will help your webpage.

What is preload?

Preload essentially tells the browser that there’s this file that you need to load, but you don’t want to load it just yet. Instead, you just want it there while the rest of the page loads first. Then at some point you’re going to call it like a normal call to an external stylesheet.

This process keeps the page loading while the browser makes calls to get external assets. Essentially, it’s lazy loading for CSS and even JavaScript. And it makes the site faster, which is a plus for everyone.

How to preload your CSS

So, now how to you preload your CSS and other external resources? The answer is simpler than you think. Currently, you load CSS and JS through the link tag. So, to preload those resources, all you need is to change the rel attribute to preload and add the as=”style” attribute (or as=”script” for JavaScript).

That’s it, right? Well not quite.

If you try to load a page now, you’re not going to get your CSS or JavaScript loaded. That’s because it hasn’t really been called yet. We need to trigger that call.

For CSS, all we need to do is add the onload=”this.rel = ‘stylesheet’” attribute to the link tag. For JavaScript, things get a bit trickier. Instead, you’ll need to use the following code.

<script>   var usedLaterScript = document.createElement('script');   usedLaterScript.src = 'used-later.js';   document.body.appendChild(usedLaterScript); </script>

And that’s it. Now you can “lazy load” your CSS and JavaScript.

Why should you do this?

Now, why should you go through all this trouble? Well the answer is speed. Speed is what we’re after. How can we make cool and informative websites but keep them loading fast?

Preloading your CSS (and other external resources) helps the page load quicker. When you’re using preload, you’re moving the CSS load to after the window.load event, meaning the rest of the page can load as well as the CSS.

This change might not be noticeable on small websites with small stylesheets. But with bigger stylesheets and websites, and modern web applications, this change can really help accelerate the page load speed. And that means everything these days.

So try it and see what happens. I think you’ll be happy with the results.

Leave a Reply

Your email address will not be published. Required fields are marked *