1

My group is adding the following into the head area:

    <script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-xxx-1']);
        _gaq.push(['_trackPageview']);
        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
    </script>

 </head>

When asked about this they are saying that it is okay to have there as it does not run synchronously. Is this correct or should the code be moved to the footer?

1 Answers1

0

This is correct because the script is loading asynchronously and an asynchronous load doesn't hold/hang the page loading process so it won't decrease the performance.

Here is an answer about Asynchronous Vs. Synchronous and here is a very nice article about loading javascript with more technics and examples.

I think this is a better approach (an unobtrusive lazy load pattern)

(function() {
    function async_load(){
        // ...
    }
    if (window.attachEvent)
        window.attachEvent('onload', async_load);
    else
        window.addEventListener('load', async_load, false);
})();

But when you are loading a script synchronously (classic) like this

<script type="text/javascript" src="yourScript.js"></script>

it's a good idea to keep it in the footer, so it won't hang the page load.

You can also use async in the script to allow the synchronous load but it's not supported by all browsers. Here is another answer about it.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307