6

I have an HTML file which is linked to CSS file and also to JavaScript file.

Is JavaScript executed first and then the CSS is applied, or vice versa ?

Is there any way to change the order ?

Thanks !

2
  • 2
    I think that depends heavily on the browser and the structure of the document. Why are you asking this? How are your JavaScript file and your style sheet connected? Commented Apr 13, 2010 at 15:30
  • Refer to this answer at stackoverflow.com/a/1795502/1074998 , it's executed in top-down order, regardless of css or js. Commented Oct 20, 2017 at 17:43

3 Answers 3

8

It's generally considered a good idea to import your scripts as late as possible, and your stylesheets as early as possible. If possible, in fact, you should stick all your script imports at the very end of the <body>. I find that problematic when there are components pulled into the page that want to be able to drop little script blocks that reference jQuery (for example).

If your stylesheets are first, that helps make sure the browser applies styles before showing anything to the user. Conversely, by including scripts last, you defer that potentially slow script processing until after the point where the user gets to see something on the screen.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, I find that the jQuery script is the only one I include in the <head> anymore (and using a Google or MS CDN source in hopes that people have a cached copy)
@great_llama — Are cached copies interchangeable between domains? That would highly surprise me.
@FrankConijn yes, that's the whole point of loading from a CDN. Note that there are security measures available (secure checksums) that help ensure that you're getting the code you expect to get.
4

The JavaScript gets executed when the <script> element is parsed. Some of the JS might set up event handlers to run some JS when events happen.

CSS is applied to the live DOM. Changes to the DOM get CSS applied automatically. Changes to CSS apply to the whole DOM automatically.

2 Comments

I still don't understand. If, for example, the CSS sets a color of <h1> element and the JavaScript also sets a color of the same <h1> element, what will be the color ? Is this deterministic among different browsers ? Thanks !
JavaScript cannot set the color of an element. It can modify CSS, in which case the normal cascade rules apply.
2

Yahoo's research into speeding-up page loading times should be very helpful, and they explain things much clearer than I can.

http://developer.yahoo.com/performance/rules.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.