Call CSS first

> > Ensure the browser gets CSS first

Updated: April 21st 2016


Why should CSS be called first?

  • Because all CSS must be dealt with by the browser before a user can see anything on their screen.

Calling CSS before javascript (or anything else)

A basic issue that delays CSS is simply that a webpage is calling other resources before it calls the CSS.

This is referring to the order in which calls for resources appear in the HTML.

Let's use a webpage has one image, one css file, and one javascript file to illustrate.

In the above image the call for the CSS file is taking place before (higher on the page) than the call to the image file and the call to the javascript file.

In reality your pages are likely calling several things, even dozens of external resources.

Ensuring the calls for CSS files come first helps ensure the browser gets it first.

This saves time by reducing network calls and not letting javascript activity delay the browser from getting CSS.

Network calls

As an oversimplified example, let's just say that each network call (getting each file) takes one second.

  • If we call the CSS file first, the browser will get the CSS in one second.
  • If we call the javascript first, the browser will get the CSS in two seconds (one second to retrieve the javascript + one second to retrieve the CSS).
  • If we call the javascript and the image before the CSS then the browser will get the CSS in three seconds.

This matters because the browser can not display anything at all until it first has the CSS.

Our (admittedly oversimplified) example webpage, with the same resources will load in either one, two or three seconds. Simply by changing the order of how things are called.

Each thing your page loads takes some amount of time. To get CSS to the browser first, we must remove anything that is loading before it. This is typically as simple as changing the order in which your HTML calls resources.

Even though browsers have methods that try to solve this fundamental problem, the best practice is to simply put all calls for CSS first.

Javascript activity delay

If a browser has to download a javascript file before the CSS, it is bad for the network time but it can get much worse.

Imagine that we call a javascript file before a CSS file and the javascript is actually saying "wait for one second" or the javascript file is calling other javascript files.

These javascript activities will just further delay the browser from getting the CSS that it needs to display the page.

For these reasons, we should always place the calls for CSS before the calls for anything else.

Patrick Sexton by