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 !

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • 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? – Pekka Apr 13 '10 at 15:30
  • Refer to this answer at https://stackoverflow.com/a/1795502/1074998 , it's executed in top-down order, regardless of css or js. – 林果皞 Oct 20 '17 at 17:43

3 Answers3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I still don't understand. If, for example, the CSS sets a color of

    element and the JavaScript also sets a color of the same

    element, what will be the color ? Is this deterministic among different browsers ? Thanks !

    – Misha Moroshko Apr 14 '10 at 08:59
  • JavaScript cannot set the color of an element. It **can** modify CSS, in which case the normal cascade rules apply. – Quentin Apr 14 '10 at 09:07
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

Mathew
  • 8,203
  • 6
  • 37
  • 59