Question

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.

Was it helpful?

Solution

The document itself will not load any 'faster' as far as when DomReady fires, but the document and assets will load ahead of your not-so-urgent-stuff.js making 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?

OTHER TIPS

The performance rule is to defer loading as much js as you can.

In older browsers downloading the js will prevent other files from being downloaded in parallel and block the UI while it's being downloaded.

Even on modern browser, the parsing and execution of the js will stop rendering.

One of the aims of moving the js to the bottom is to delay this UI thread work. It also prevent broken thrid parties from screwing up your page load.

@souders has written quite a lot on this topic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top