Reputation: 1308
Based on this blog post Optimizing the asynchronous Google Analytics snippet and the comments, I have come up with this optimized Google Universal Analytics snippet that is shorter, runs faster (albeit slightly) and breaks IE6/IE7/oldIE8*
compatibility.
+function(G,o,O,g){G.GoogleAnalyticsObject=O;G[O]||(G[O]=function(){(G[O].q=G[O].q||[]).push(arguments)});G[O].l=+new Date;g=o.createElement('script');g.src='//www.google-analytics.com/analytics.js';o.documentElement.appendChild(g)}(this,document,'ga');
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
However, when the snippet above is placed in the <head>
, it inserts the Universal Analytics script as a child not of <head>
, not of <body>
, but of <html>
, right between </head>
and <body>
.
Although IE8+ and modern browsers seems to have no problem with that, I am still worried that it might break older mobile browsers or some other obscure and non-IE browser somewhere.
Is there anywhere in the HTML specs that describe how a browser should react to tags placed outside <head>
and <body>
?
*
Unpatched vanilla IE8 on Windows XP will abort page loading just like IE6 and IE7 and spew an HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917)
error. After installing a cumulative security update, starting with KB980182 first released in April 2010 and included in subsequent updates (KB982381, KB2183461, KB2360131, KB2416400, KB2482017, KB2497640, KB2530548, KB2559049, KB2586448, KB2618444, KB2647516, KB2675157, KB2699988, KB2722913, KB2744842, KB2761465, KB2792100, KB2809289, KB2817183, KB2829530, KB2838727, KB2846071, KB2862772, KB2870699, KB2879017, KB2888505, KB2898785, KB2909921), fixes the problem.
Upvotes: 3
Views: 5184
Reputation: 4785
Yes and Its better to have Javascript
script tag at bottom
Reference yahoo developers
Upvotes: 3
Reputation: 8153
this is considered best practice for wpo, as the body will render before firing off the script element.
i'm not sure if its valid, you'll have to check spec, or run it through the validator...but its pretty much sop
Upvotes: 0