Smart way to add the tracking code for Google analytics


/ Published in: JavaScript
Save to your folder(s)

Asynchronous Google analytics tracking

based entirely on examples from code.google.com and yoast.com
http://yoast.com/wordpress/google-analytics/
http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html

notes from code.google.com
If you prefer to put the Analytics snippet at the bottom of the page, you should know that you don't have to put the whole snippet at the bottom. You can still keep most of the benefits of asynchronous loading by splitting the snippet in half—keep the first half at the top of the page and move the rest to the bottom. Because the first part of the tracking snippet has little to no effect on page rendering, you can leave that part at the top and put the part of the snippet that inserts ga.js at the bottom.

Both pieces of code need to be wrapped in their own script tags, but only the last six lines of the original asynchronous snippet need to be moved to the bottom. All the lines that push methods onto _gaq can stay at the top.


Copy this code and paste it in your HTML
  1. <html>
  2.  
  3. <head>
  4. <script type="text/javascript">//<![CDATA[
  5. var _gaq = _gaq || [];
  6. _gaq.push(['_setAccount','UA-xxxxxxx-x']);
  7. _gaq.push(['_trackPageview'],['_trackPageLoadTime']);
  8. (function() {
  9. var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  10. ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  11. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  12. })();
  13. //]]></script>
  14. </head>
  15.  
  16. <body>
  17.  
  18. <p>Page Content</p>
  19.  
  20. <script type="text/javascript"> (function() {
  21. var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  22. ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  23. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  24. })();
  25. </script>
  26. </body>
  27. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.