Google Analytics claims to have a way to asynchronously load their script. You put this at the bottom of <body>:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') +
'.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
The async attribute works in Firefox 3.6+. I claim that it’s not asynchronous at all on my FF 3.6.8. Here’s my test. I changed the the code to:
(function() {
var ga = document.createElement('script');
ga.src = '/sleep.php';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
sleep.php:
<?php
sleep(5);
?>
This has slowed down my website by 5 seconds! My main JS code relies on the window load event to manipulate the DOM. This simulation of a slow loading Google Analytics has pushed back the window load event by 5 seconds. And believe me, Google Analytics has been slow on more than one occasion! So am I just not understanding what the async attribute is supposed to do?