Zach’s ugly mug (his face)

Zach Leatherman

Speed up Including Google Analytics

01 Nov 2007 Zach Leatherman


This article is old and may contain information that is outdated, irrelevant, or—dare I say it—no longer accurate. Read with care!

Have you ever noticed that your homepage hangs when including the Google Analytics JavaScript file? I think a few people have noticed a delay. Well, let’s try something different. Let’s create the script node dynamically using DOM methods and put a timeout on this creation so that it inserts just enough delay so that your page won’t hang (we’ll move out of the current execution path with the timeout, thus allowing your page to finish loading). The obvious benefit here is that even when the Google servers lag a little bit serving you the JavaScript file, your page will appear as if it has already finished loading. Given optimally performing Google Servers, this method will perform slower most of the time, but it shines in those rare instances where there is a bit of a delay. Give it a try, and let me know if it works any better.

Of course, remember to put near the end of your <body>, and not directly in your <head>.

<script type="text/javascript">
        var node = document.createElement("script");
        node.src = '';
        //for SSL
        //node.src = '';
        node.type = 'text/javascript';
        var init = setInterval(function()
            _uacct = 'UA-XXXXXX-X'; // INSERT YOUR CODE HERE
            if(typeof urchinTracker != 'undefined') {
        }, 100);
    }, 0);

Try it on my benchmark page.