jquery ajax async vs html5 script async

jquery ajax async vs html5 script async

Firefox is now supporting the html5 proposed async attribute on scripts, which allows them to execute in a non-blocking fashion. The syntax is

  1. <script async=""> ... </script>

(Note, not async="true", although async="async" is valid.)

Here's how google analytics recommend using their tracking code asynchronously:

  1. var ga = document.createElement('script');
  2. ga.type = 'text/javascript';
  3. ga.async = true;
  4. ga.src = ('https:' == document.location.protocol ?
  5. 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  6. (document.getElementsByTagName('head')[0] ||
  7. document.getElementsByTagName('body')[0]).appendChild(ga);

It's a rather ugly way of injecting a script into the head, but note the async=true bit. In jquery a neater way would be:

  1.         $.ajax({
  2.             cache: true,
  3.             async: true,
  4.             dataType: "script",
  5.             url: 'https://ssl.google-analytics.com/ga.js'
  6.         });
... which does almost exactly the same thing, except the script is just a normal script. I've just put the async in here as illustration that it's related to the ajax call, nothing to do with the returned script.

Anyway, can we do something equivalent of google's code? An extra parameter on getScript is the most obvious place, but currently getScript (which just wraps an ajax call) defaults to cache:false, so it's actually not much use - but that's a separate issue.

AJP