Saturday, September 25, 2010

Where to put your Javascript code?

Let me first answer the question,

“JavaScript code is  supposed to go at the bottom of your page!”

The first time I read this, this seemed strange to me. I was learned that  JavaScript’s true home was in the <head> element. In fact, many samples still promote this approach.

So why should you put it at the bottom of the page?   Therefore we have to look at the way that a browser works. When a browser loads a document there are only so many thread for processing the document. So any time the browser spends parsing JavaScript is time it could be using to make the page look right.  Also, with some browsers, when the browser is loading JavaScript, ALL OTHER ACTIVITY STOPS.  Nothing else is downloaded, the browser is at a standstill until all the script is parsed.

For simple pages, it doesn’t make a noticeable difference.  But if you have a lot of JavaScript on the page, the responsiveness impact could be significant.  

No comments: