views:

65

answers:

2

This question is sort of a tangent to Browser support for <script async=“true” />?.

I've seen a few scripts lately that do something like this:

var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://www.example.com/script.js';
document.getElementsByTagName('head')[0].appendChild(s);

This is a common way to add a script to the DOM dynamically, which, IIRC from Steve Souders's book "Even Faster Web Sites," prompts all modern browsers to load the script asynchronously (i.e., not blocking page rendering or downloading of subsequent assets).

If I'm correct in that, does the s.async = true statement have any use? Wouldn't it be redundant, even for the browser(s) that support that property, since dynamically appended a script should already trigger asynchronous downloading?

+1  A: 

I believe you're correct.

In Steve's own examples he does not set the async attribute before attaching the script tag to the head element.

My understanding of the async atttribute is that it's a way of signaling to the browser that you don't intend to manipulate the page by using document.write so that it can continue rendering instead of halting to load the script. See the documentation for the script element at mdc which contains a bit more on the document.write/async issues.

Note that with your technique you shouldn't use document.write anyway since you've got no way of knowing where in the page lifetime your script will be loaded.

Markus Olsson
Markus - great answer, and I appreciate your contribution! I looked into this further, and made some discoveries - please read the answer I just added.
Bungle
+1  A: 

Interesting - I think it turns out that I was wrong in my assumptions.

Based on this thread in the jQuery developers' forum:

http://forum.jquery.com/topic/jquery-ajax-async-vs-html5-script-async

it looks like the async property has been discovered to have an effect on dynamically-appended scripts, at least in Firefox (and potentially Opera, though it doesn't yet support the property).

The forum thread also cites Google's asynchronous tracking code implementation, which, although it appears to make use of the async property in the appropriate context, actually appears to get the syntax wrong. Google uses:

ga.async = true;

when apparently that doesn't work; the proper method would be to use either:

ga.async = 'async';

or

ga.setAttribute('async', 'async');

So, based on my current understanding, not all browsers will actually execute dynamically-appended scripts immediately upon their insertion into the DOM in all cases; Firefox (and eventually Opera) will need the async property to be set to ensure that this always happens.

More info on Firefox's implementation of async here:

https://bugzilla.mozilla.org/show_bug.cgi?id=503481

Bungle
Very interesting thread over at jQuery forums. Guess my google fu wasn't strong enough to find it ;) Thanks!
Markus Olsson