10

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?

palswim
  • 11,856
  • 6
  • 53
  • 77
janfrode
  • 348
  • 1
  • 2
  • 11

3 Answers3

12

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.

mtmacdonald
  • 14,216
  • 19
  • 63
  • 99
  • 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." – Vsevolod Golovanov Oct 07 '15 at 15:46
7

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.

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • If the scripts are executed on DOM ready, you might just want to stick them all just before the `

    ` tag. It's a bit of savings, but every second counts.

    – zzzzBov Nov 16 '10 at 20:37
  • +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. – mtmacdonald Nov 13 '12 at 16:00
0

It doesn't matter, although if loading takes a while, the user might see his page change appearance and wonder why. I'd put the CSS files first to have the style definitions in place before any DOM manipulation, most likely minimizing the visible change as the page loads, but it doesn't really matter in the end.

palswim
  • 11,856
  • 6
  • 53
  • 77