views:

247

answers:

3

How do I prevent JavaScript from blocking other JavaScript's from starting to download?

I have the following on my web site:

<html>
<body>
....
<script type="text/javascript" src="http://example.com/ex.js"&gt;&lt;/script&gt;
<script type="text/javascript" src="http://google.com/google-maps.js"&gt;&lt;/script&gt;
</body>
</html>

When I use the YSlow Firefox add-on, I can see from the network traffic tab that the google.com/google-maps.js JavaScript won't start downloading until ex.js has finishes downloading.

Question: How can I have both ex.js and google-maps.js begin downloading immediately and in parallel?

A: 

The JavaScript files will always download in the order they are specified.

Trevor
How can I have the JS files download in parallel?
Teddy
@Teddy: You can't. That's a function of the browser, not the markup. IIRC, Chrome and Safari 4 will do some parallel loading of external JavaScript, but you can't force other browsers to behave in that manner.
Eric Kolb
@Eric Kolb, check out @womp - he seems to have a small script that does force other browsers to download in parallel.
Teddy
Well, it's not *my* script.. but it should do the job
womp
+2  A: 

It's ugly, but you can get scripts to download in parallel by injecting the DOM elements ... using javascript.

Check out this blog post for a working example.

womp
+2  A: 

This is normal for inline scripts in HTML. You could add the scripts dynamically using the following code:

<script type="text/javascript">
    var head  = document.getElementsByTagName("head")[0]; 
    var sTag1 = document.createElement("script");
    var sTag2 = document.createElement("script");
    sTag1.type = sTag2.type = "text/javascript";
    sTag1.src = "http://example.com/ex.js";
    sTag2.src = "http://google.com/google-maps.js";
    head.appendChild(sTag1);
    head.appendChild(sTag2);
</script>

This could cause unexpected results, however - they may not be downloaded and parsed in the correct order, which is important if script 2 references variables or functions from script 1.

If you just want your HTML to load before the scripts load, keep them sequential and put them at the bottom of your HTML file, not in the head tag. This will load the page before downloading and parsing the script. See http://developer.yahoo.net/blog/archives/2007/07/high_performanc_5.html.

Andy E
What are the pro/con's of using this versus what @womp recommends. The code looks drastically different
Teddy
@Teddy - looking at the link womp mentioned, they are functionally the same, but that blog post uses a loop to iterate over several script sources and then creates the elements in a simlar way to my own code above. It looks like it only does that for Firefox and Opera though, not Internet Explorer or others, for which it writes the HTML directly with `writeLn`.
Andy E