[javascript] Should CSS always preceed Javascript?

In countless places online I have seen the recommendation to include CSS prior to JavaScript. The reasoning is generally, of this form:

When it comes to ordering your CSS and JavaScript, you want your CSS to come first. The reason is that the rendering thread has all the style information it needs to render the page. If the JavaScript includes come first, the JavaScript engine has to parse it all before continuing on to the next set of resources. This means the rendering thread can't completely show the page, since it doesn't have all the styles it needs.

My actual testing reveals something quite different:

My test harness

I use the following Ruby script to generate specific delays for various resources:

require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'date'

class Handler  < EventMachine::Connection
  include EventMachine::HttpServer

  def process_http_request
    resp = EventMachine::DelegatedHttpResponse.new( self )

    return unless @http_query_string

    path = @http_path_info
    array = @http_query_string.split("&").map{|s| s.split("=")}.flatten
    parsed = Hash[*array]

    delay = parsed["delay"].to_i / 1000.0
    jsdelay = parsed["jsdelay"].to_i

    delay = 5 if (delay > 5)
    jsdelay = 5000 if (jsdelay > 5000)

    delay = 0 if (delay < 0) 
    jsdelay = 0 if (jsdelay < 0)

    # Block which fulfills the request
    operation = proc do
      sleep delay 

      if path.match(/.js$/)
        resp.status = 200
        resp.headers["Content-Type"] = "text/javascript"
        resp.content = "(function(){
            var start = new Date();
            while(new Date() - start < #{jsdelay}){}
          })();"
      end
      if path.match(/.css$/)
        resp.status = 200
        resp.headers["Content-Type"] = "text/css"
        resp.content = "body {font-size: 50px;}"
      end
    end

    # Callback block to execute once the request is fulfilled
    callback = proc do |res|
        resp.send_response
    end

    # Let the thread pool (20 Ruby threads) handle request
    EM.defer(operation, callback)
  end
end

EventMachine::run {
  EventMachine::start_server("0.0.0.0", 8081, Handler)
  puts "Listening..."
}

The above mini server allows me to set arbitrary delays for JavaScript files (both server and client) and arbitrary CSS delays. For example, http://10.0.0.50:8081/test.css?delay=500 gives me a 500 ms delay transferring the CSS.

I use the following page to test.

<!DOCTYPE html>
<html>
  <head>
      <title>test</title>
      <script type='text/javascript'>
          var startTime = new Date();
      </script>
      <link href="http://10.0.0.50:8081/test.css?delay=500" type="text/css" rel="stylesheet">
      <script type="text/javascript" src="http://10.0.0.50:8081/test2.js?delay=400&amp;jsdelay=1000"></script> 
  </head>
  <body>
    <p>
      Elapsed time is: 
      <script type='text/javascript'>
        document.write(new Date() - startTime);
      </script>
    </p>    
  </body>
</html>

When I include the CSS first, the page takes 1.5 seconds to render:

CSS first

When I include the JavaScript first, the page takes 1.4 seconds to render:

JavaScript first

I get similar results in Chrome, Firefox and Internet Explorer. In Opera however, the ordering simply does not matter.

What appears to be happening is that the JavaScript interpreter refuses to start until all the CSS is downloaded. So, it seems that having JavaScript includes first is more efficient as the JavaScript thread gets more run time.

Am I missing something, is the recommendation to place CSS includes prior to JavaScript includes not correct?

It is clear that we could add async or use setTimeout to free up the render thread or put the JavaScript code in the footer, or use a JavaScript loader. The point here is about ordering of essential JavaScript bits and CSS bits in the head.

This question is related to javascript css performance

The answer is


Personally, I would not place too much emphasis on such "folk wisdom." What may have been true in the past might well not be true now. I would assume that all of the operations relating to a web-page's interpretation and rendering are fully asynchronous ("fetching" something and "acting upon it" are two entirely different things that might be being handled by different threads, etc.), and in any case entirely beyond your control or your concern.

I'd put CSS references in the "head" portion of the document, along with any references to external scripts. (Some scripts may demand to be placed in the body, and if so, oblige them.)

Beyond that ... if you observe that "this seems to be faster/slower than that, on this/that browser," treat this observation as an interesting but irrelevant curiosity and don't let it influence your design decisions. Too many things change too fast. (Anyone want to lay any bets on how many minutes it will be before the Firefox team comes out with yet another interim-release of their product? Yup, me neither.)


Here is a SUMMARY of all the major answers above (or maybe below later :)

For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.

For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).

For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)

There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.

So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.


Steve Souders has already given a definitive answer but...

I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.

Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.

How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...

The first file downloaded should get the connection used for the html page, and the second file downloaded will get the new connection. (Flushing the early alters that dynamic, but it's not being done here)

In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away, in older browsers this isn't true and the second connection will have the overhead of being opened.

Quite how/if this affects the outcome of the tests I'm not sure.


Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.

The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.

All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.


Updated 2017-12-16

I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.

Synchronous <script src...> will block downloading of the resources below it until it is downloaded and executed

This is no longer true. Have a look at the waterfall generated by Chrome 63:

<head>
<script src="//alias-0.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=3"></script>
</head>

Chrome net inspector -> waterfall

<link rel=stylesheet> will not block download and execution of scripts below it

This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:

<link href="//alias-0.redacted.com/payload.php?type=css&amp;delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;block=1000"></script>

Chrome dev tools -> performance


Keeping the above in mind, the results in OP can be explained as follows:

CSS First:

CSS Download  500ms:<------------------------------------------------>
JS Download   400ms:<-------------------------------------->
JS Execution 1000ms:                                                  <-------------------------------------------------------------------------------------------------->
DOM Ready   @1500ms:                                                                                                                                                      ?

JS First:

JS Download   400ms:<-------------------------------------->
CSS Download  500ms:<------------------------------------------------>
JS Execution 1000ms:                                        <-------------------------------------------------------------------------------------------------->
DOM Ready   @1400ms:                                                                                                                                            ?

Is the recommendation to include CSS before JavaScript invalid?

Not if you treat it as simply a recommendation. But if your treat it as a hard and fast rule?, yes, it is invalid.

From https://developer.mozilla.org/en-US/docs/Web/Reference/Events/DOMContentLoaded

Stylesheet loads block script execution, so if you have a <script> after a <link rel="stylesheet" ...> the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded.

It appears that you need to know what each script relies on and make sure that execution of the script is delayed until after the right completion event. If the script relies only on the DOM, it can resume in ondomready/domcontentloaded, if it relies on images to be loaded or stylesheets to be applied, then if I read the above reference correctly, that code must be deferred until the onload event.

I don't think that one sock size fits all, even though that is the way they are sold and I know that one shoe size does not fit all. I don't think that there is a definitive answer to which to load first, styles or script. It is more a case by case decision of what must be loaded in what order and what can be deferred until later as not being on the "critical path".

To speak to the observer that commented that it is better to delay the users ability to interact until the sheet is pretty. There are many of you out there and you annoy your counterparts that feel the opposite. They came to a site to accomplish a purpose and delays to their ability to interact with a site while waiting for things that don't matter to finish loading are very frustrating. I am not saying that you are wrong, only that you should be aware that there is another faction that exists that does not share your priority.

This question particularly applies to all of the ads being placed on web sites. I would love it if site authors rendered just placeholder divs for the ad content and made sure that their site was loaded and interactive before injecting the ads in an onload event. Even then I would like to see the ads loaded serially instead of all at once because they impact my ability to even scroll the site content while the bloated ads are loading. But that is just one persons point of view.

  • Know your users and what they value.
  • Know your users and what browsing environment they use.
  • Know what each file does, and what its pre-requisites are. Making everything work will take precedence over both speed and pretty.
  • Use tools that show you the network time line when developing.
  • Test in each of the environments that your users use. It may be needed to dynamically (server side, when creating the page) alter the order of loading based on the users environment.
  • When in doubt, alter the order and measure again.
  • It is possible that intermixing styles and scripts in the load order will be optimal; not all of one then all of the other.
  • Experiment not just what order to load the files but where. Head? In Body? After Body? DOM Ready/Loaded? Loaded?
  • Consider async and defer options when appropriate to reduce the net delay the user will experience before being able to interact with the page. Test to determine if they help or hurt.
  • There will always be trade offs to consider when evaluating the optimal load order. Pretty vs. Responsive being just one.

The 2020 answer: it probably doesn't matter

The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.

I included a more detailed writeup on my blog


I think this wont be true for all the cases. Because css will download parallel but js cant. Consider for the same case,

Instead of having single css, take 2 or 3 css files and try it out these ways,

1) css..css..js 2) css..js..css 3) js..css..css

I'm sure css..css..js will give better result than all others.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder