Skip to Content

How to Load CSS and JavaScript Faster


This tutorial walks you through a series of tools and tips to optimize the way you load CSS and JavaScript to help your web pages load faster.

Minifying your JavaScript and CSS

The reason most CSS and JavaScript is not minified is because it enables humans to read and write code. Your device, however, doesn't care about human-readability. From a machine's perspective, CSS and JavaScript that is not minified makes files larger than required.

Optimizing CSS and JavaScript for the browser involves more than just the removal of new line characters, white space, shortening variable names, combining duplicate CSS, etc. It’s all quite simple and involves one goal: less characters and as a result, smaller file sizes and faster-loading web pages.

So “minifying” JavaScript and CSS ultimately leads to faster page load speed. Does that mean we have to go through all of our code and minify it ourselves? No.

Here’s a popular list of CSS and JS tools that do the “minifying” for you:

Alternatively, the PageSpeed Module, integrates with an Apache or Nginx web server to automatically optimize your site, including resource minification.

CSS

Your browser waits for all CSS to be loaded before it can begin rendering a web page. The more CSS you have, the longer it will take for your web page to be styled. Let’s discuss some workarounds to help load your CSS faster (aside from “minifying”):

Media Types and Queries

When including your styles, the media attribute can be very helpful. By marking it as "print" the browser will not have to wait until it is loaded.

Media Queries allow you to load CSS depending on the size of the viewport and in an increasingly mobile age, it is highly recommended you use them. Based on your query, your browser decides if it has to load the CSS or not.

Deliver and Include CSS as Early as Possible

Since the browser has to wait for all CSS to be loaded, it's important to provide it as quickly as possible. A very simple way to make sure the browser receives CSS as early as possible is by including it in the HEAD section of your HTML document. This way, the browser will start loading CSS as soon as possible.

JavaScript

Much like CSS, a browser will stop building a page until it loads and parses the JavaScripts it encounters. When loaded and parsed your browser will continue to render the web page.

Load JavaScripts at the Bottom

Always include JavaScript resources at the very bottom of your HTML document before the closing body tag.

Including Scripts with ´async´

Use the “async” attribute so the browser knows which JavaScripts should not block the rendering process.


Scott Madara
Contributions Editor here at Solodev. Want to be featured on the Solodev Blog? Get in touch.
Follow me on Twitter

Sign up to explore

Create an account in seconds and start building today.

Sign up for Solodev
Solodev Logo

©2024 Solodev. All rights reserved worldwide.