Speed up Including Google Analytics

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">
(function()
{
    setTimeout(function()
    {
        var node = document.createElement("script");
        node.src = 'http://www.google-analytics.com/urchin.js';
        //for SSL
        //node.src = 'https://ssl.google-analytics.com/urchin.js';
        node.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(node);
        var init = setInterval(function()
        {
            _uacct = 'UA-XXXXXX-X'; // INSERT YOUR CODE HERE
            if(typeof urchinTracker != 'undefined') {
                urchinTracker();
                clearInterval(init);
            }
        }, 100);
    }, 0);
})();
</script>

Try it on my benchmark page.

This entry was posted in JavaScript and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.
  • If you found this article useful, you should subscribe to my feed (or get an e-mail). I'm also on Twitter and GitHub.
  • About the Author

    Zach Leatherman is a Professional Front End Engineer. He loves building for the web, and has been contributing to the community through his blog since February 2007. Despite his propensity for software, he has a Bachelors degree in Computer Engineering and is currently on the User Experience Team at Union Pacific Railroad. The views expressed on this website do not represent the views of his employer.

    He enjoys spending time with his beautiful wife Traci and their two Great Danes, Roxie and Ella. They also have a cat, a rabbit, goldfish, and one or more tarantulas. Read more »

One Trackback

  1. [...] First of all, Google makes it very easy to embed metrics into your website, by copying and pasting a bit of javascript into your page. If you’re running into delays downloading the urchin.js file, you can use tricks such as Speed up Google Analytics with dynamic includes. [...]