lyncd

Posts tagged ‘google-analytics’

Better Google Analytics JavaScript that doesn’t block page downloading

If you saw Steve Souders’ March 5 talk at Google and have ever used Google Analytics, then you were probably amused when he used GA’s JavaScript insertion code as his “wrong” counterexample. Well, at least I was, and somebody else mentioned it in the Q&A so I figure I’m not the only one.

The GA insertion code that Google gives you to put on your site does a couple of bad things: First, it uses document.write, and second, it loads ga.js directly, which blocks browsers from doing any page rendering or downloading of other page components (images, scripts, stylesheets) during the whole time it takes ga.js to download and execute. In other words, Google Analytics makes your pages load slower!

Using Steve’s best practices, I’ve coded up a better version that does DOM insertion of the script tag and uses the “script onload” technique to initialize the tracker, so that it doesn’t block I/O, and you can inline it anywhere on the page or even load it from an external file. You can choose to lazy-load GA whenever you want — for instance, even after window.onload fires — so that it’s totally asynchronous and doesn’t interfere with page rendering at all. more …

Filed under: Code.  Tagged: , , .