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
- <script async=""> ... </script>
(Note, not async="true", although async="async" is valid.)
Here's how google analytics recommend using their tracking code asynchronously:
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:
- var ga = document.createElement('script');
- ga.async = true;
- ga.src = ('https:' == document.location.protocol ?
- 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
- (document.getElementsByTagName('head') ||
... 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.
- cache: true,
- async: true,
- dataType: "script",
- url: 'https://ssl.google-analytics.com/ga.js'
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.