Where to include JavaScript files in a document

Today I thought we’d talk about how, or rather were in the document, to include JavaScript files.

Getting head

I assume that each and everyone of you were taught to include your JavaScript files within the head element, and up to now, as far as you know, it has worked just fine for you.


	<script type="text/javascript" src="js/DOMAssistant.js"></script>

Going down?

However, another alternative approach started figuring on the web where people included their JavaScript files just before the closing body tag instead.


	<script type="text/javascript" src="js/DOMAssistant.js"></script>

There are a number of reasons why this way of doing it is attractive:

  • There’s no need to have a check if the DOM is loaded, since by having the scripts at the end, you know for sure it is.
  • A JavaScript script file has to be loaded completely before a web browser even begins on the next JavaScript file. The effect of this, if the JavaScript files are included at the top of the document, is that it will be a visual delay before the end user sees the actual page. This is completely avoided if you include the JavaScript files at the end of the document.

It is also a recommended by Yahoo’s Best Practices for Speeding Up Your Web Site: Put Scripts at the Bottom.

Not satisfied?

While including the JavaScript files at the bottom helps us around the problem of delaying the page rendering, thus giving the impression that each page in the web site loads faster, it does have a drawback.

If the page is visible to the end user, but the JavaScript files haven’t finished loading yet, no events have been applied to the elements yet (because everyone uses an unobtrusive approach, right?) and the user might start clicking around and not getting the expected results.

If you have proper fallbacks, e.g. a link element which gets content via AJAX if JavaScript is supported and the proper event has been applied, otherwise it’s a normal link leading to another page, then the problem isn’t that bad. Still somewhat annoying, though.

I’ve been swaying back and forth with my opinions about how to tackle this, and my conclusion is that every end user will be affected by page rendering delays, white pages etc, while only the fast clicking types will ever experience the fallback solution when content is visible but the JavaScript files haven’t been completely loaded.

Therefore, I’m including my JavaScript files at the bottom of a web page.

How do you do it? And, do you have any good suggestions for the problem described with the web page being visible but the JavaScript files not loaded?

Posted in Developing,JavaScript,Technology |

Leave a Reply

Your email address will not be published. Required fields are marked *