I’ve read that it is bad practice, but usually harmless, to place most of a page’s <script> after the <body>. Since the consequences seem not to be big, I am wondering if I have a compelling reason to try it: page load speed.
My question is: will the pre-body javascript execute any faster if the rest of the javascript comes after the body? Or to put it differently: is the faux document below any faster in loading than if I had placed all the script in the head?
<html>
<head>
<script src="urgent-stuff.js"/>
</head>
<body>
<p>Lots of great content</p>
</body>
<script src="not-so-urgent-stuff.js">
</html>
Note: I am using jQueryMobile for my site (=mobile app). This framework puts the entire site in one document, and dolls up the basic HTML of each page with style and interaction based mostly on element “data-” attributes before that page is shown.
The jQM javascript is obviously part of the urgent stuff that goes into the < head >. jQueryMobile has its own ‘getting started’ event called ‘pageinit’, which it says fires well before the regular ‘document ready’ in regular jQuery.
The document itself will not load any ‘faster’ as far as when
DomReadyfires, but the document and assets will load ahead of yournot-so-urgent-stuff.jsmaking it appear to load faster and making content available right away.The fastest way to load content to the browser is not to block the browser with successive script loads – any time you call scripts from a
<script>tag the browser must fetch the resource and execute it in series with any other content.You can visualize this with a number of tools such as Yslow. Yslow itself provides a great resource on how to optimize placement of your content in your documents.
http://developer.yahoo.com/yslow/
http://developer.yahoo.com/performance/rules.html
Edit:
This was also covered with some pretty favorable response in this related stack thread Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?