Was it helpful?

Solution

The best way to include JavaScript on your website is to include as few files as possible at the end of the page*, after all of the markup and other assets have been loaded. Doing it that way also has the added benefit of encouraging a "progressive enhancement" development model.

*Yahoo actively spends a great deal of money researching this and has dedicated, full-time people (including the brilliant Steve Souders) who publish their findings online and in book form.

OTHER TIPS

Doesn't seem like a one-size-fits-all situation, so I often resort to this famous article to help me answer questions like that:

http://developer.yahoo.com/performance/rules.html

It was mentioned in one of the podcasts, but if you host the javascript on a separate domain, or even a subdomain, the browser can open more connections and download both the js and the rest-of-the-page at the same time. This is why many people choose to link to google's instance of jQuery, rather than their own. This example also has cachine benefits, but the core principle holds.

In a nutshell the article is saying to attach <script> nodes dynamically in the DOM in order to achieve parallel downloads of script files. This works and is nothing new.

However it fails to mention the biggest drawback of the method: Although scripts will be downloaded in parallel, the order in which they are executed is not deterministic. IE will execute them in the order they finish downloading in, whereas Firefox executes them in the order they are attached in the DOM.

This is a problem. For example, say script A and script B are added using that technique. Now imagine script A is jQuery, and script B does this:

$(document).ready(function(){...})

In IE you're screwed if for whatever reason (eg, network traffic, cache miss) script B finishes downloading before script A, because it will be executed before jQuery has been loaded.

See this article for a better explanation.

Rex M's answer is the way to go.

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