Order of loading external CSS and JavaScript files

13,133

Solution 1

Check out Yahoo's Best Practices for Speeding Up Your Web Site, they recommend loading your css first (preferably in the header), and your js last (after all the content in the body). Google's best practices also recommended loading CSS first.

Solution 2

It depends. If all the JS only works on DOM ready, the order is unimportant. However, if there is any in-line javascript that changes CSS styling of DOM elements, then you'll have issues.

More practically, you should probably put the CSS first so there is less time where the user needs to experience unstyled content.

Share:
13,133
janfrode
Author by

janfrode

Updated on June 07, 2022

Comments

  • janfrode
    janfrode about 2 years

    I have a third party application that loads many css and javascript files, and I now want to optimize this by concatinating all the javascripts into one file, compressed by the yuicompressor, but ... when we have a mix like:

    <script type="text/javascript" src="script1.js"></script>
    <script type="text/javascript" src="script2.js"></script>
    <link rel="stylesheet" href="style1.css" type="text/css" />
    <script type="text/javascript" src="script3.js"></script>
    <script type="text/javascript" src="script4.js"></script>
    

    Does it matter that there's a css in the middle here? Should I concatinate and yuicompress the 4 javascripts and load them before the CSS or after?

  • zzzzBov
    zzzzBov over 13 years
    If the scripts are executed on DOM ready, you might just want to stick them all just before the </body> tag. It's a bit of savings, but every second counts.
  • mtmacdonald
    mtmacdonald over 11 years
    +1 for impact of JavaScript style manipulation. E.g. if JavasScript which alters CSS positioning runs before a dependent CSS file has loaded, unexpected rendering could occur. So CSS files should be loaded first.
  • Vsevolod Golovanov
    Vsevolod Golovanov over 8 years
    Google's best practices don't have this recommendation anymore for some reason, but Chrome 45's Audit still notes "Optimize the order of styles and scripts. The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript."