What it is the fastest asynchronous google analytics snippet? - javascript

i would to use fastest asynchronous google analytics snippet, but i'm not a good programmer and so i don't know what is the best:
A)
<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference#async-snippet-minified
B)
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
About these codes i would like to know if is a problem to put the code inside not <script> but inside <script type="text/javascript"> and if is a problem to put not before </head> (like suggested for "normal" snippet)
I hope you can help me and sorry for my english :) Thanks a lot!

The would guess the first one. It uses async and doesn't depend on DOM modification while loading the page.

For HTML5, it does not matter if you use <script> or <script type="text/javascript">.
As for where to put in your code, normally javascript should be at the bottom of the page after all of your css/html has loaded. Javascript is loaded synchronously, so each file load will stop the rest of the page from loading until that specific file is fully loaded. The async tag is not fully supported by all browsers, so I would not rely on that. Instead, you should use an asynchronous loader (like requirejs or LAB.js).
As for where you should put the google analytics script, in my experience it doesn't matter too much. It sounds like you're prematurely optimizing -- https://stackoverflow.com/a/385529/5780021. Per google's instructions, I believe it's supposed to go in the header in order to improve their statistics around page load speeds.

Related

Multiple piwik tracking js

I have wordpress plugin which outputs Piwik tracking js on client site:
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u=(("https:" == document.location.protocol) ? "https" : "http") + "://piwik.com//";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript';
g.defer=true; g.async=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="http://piwik.com/piwik.php?idsite=1" style="border:0" alt="" /></p></noscript>
The issue is that some of clients already use their own piwik tracking js, and it ends up with two piwik tracking JS outputted on their site.
Then there is conflict, because two tracking JS are writing to the same JS object "_paq"
So it would be great if there is some sollution to this like noConflict() for jQuery.
So would need the way to tell to "piwik.js" which I am including to not read from "_paq" and to read from some my custom object. So far, as I can see I would need to modify piwik.js for that.
I saw that piwik has option for multiple tracking : Multiple Piwik trackers
But I don't have control of another tracking code, I have only control of tracking JS outputed from my plugin.
So any, help would be great for this.
The only way I've been able to workaround this problem has been changing the name (choose a weird one) of the _paq variable in piwik.js and loading piwik.js synchronously.
No more collisions after that

Stop Analytics Code from Blocking other Script Execution

I am using the recommended implementation of the tracking code.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_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>
I often get this wait on load of my web pages as "waiting for www.google-analytics.com". Initially I thought it was my office firewall, but I guess it is common issue. search
My bigger concern is all the scripts on my page stop execution during this wait... which never goes away. How to fix this ?
I thought async means it will not interfere with other scripts on page.
The solution
Since you are using Jquery, wrap the google analytics code in a jQuery's window load handler:
$(window).load(function(){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_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);
})();
});
The explanation
In a comment, you pointed out that you use http://supersimpleslider.com/ and that it would not work as long as google analytics was hanging. A look at the source of that library shows this at line 86:
$(window).load(function() {
I decided to test event firing by simulating a hanging resource.
ga.php
<?php
sleep(5);
exit('content.log("ga.php available")');
?>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
window.addEventListener('load', function(){
console.log('window-load');
}, false);
window.addEventListener('DOMContentLoaded', function(){
console.log('window-DOMContentLoaded');
}, false);
</script>
<script type="text/javascript">
$(window).load(function() {
console.log('window-jquery-load');
});
$(window).ready(function() {
console.log('window-jquery-ready');
});
</script>
<script type="text/javascript">
document.addEventListener('load', function(){
console.log('document-load');
}, false);
document.addEventListener('DOMContentLoaded', function(){
console.log('document-DOMContentLoaded');
}, false);
</script>
<script type="text/javascript">
$(document).load(function() {
console.log('document-jquery-load');
});
$(document).ready(function() {
console.log('document-jquery-ready');
});
</script>
<script type="text/javascript">
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'ga.php';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
Console output
16:21:19.123 window-jquery-ready
16:21:19.124 document-jquery-ready
16:21:19.125 document-DOMContentLoaded
16:21:19.126 window-DOMContentLoaded
16:21:24.092 ga.php available
16:21:24.095 window-load
16:21:24.096 window-jquery-load
Conclusion
native DOMContentLoaded is not affected by hanging resources.
jQuery's ready is not affected by hanging resources.
window load will wait for all resources to complete.
document load will never fire (could be browser dependent though)
Since supersimpleslider is waiting for a load event on window, a hanging ga.js will impact its execution. This might also be the case for other scripts.
By inserting google analytics only at window load, we put all the scripts on the same level.
Console output after window load wrapping:
16:47:27.035 window-jquery-ready
16:47:27.036 document-jquery-ready
16:47:27.036 document-DOMContentLoaded
16:47:27.037 window-DOMContentLoaded
16:47:27.043 window-load
16:47:27.044 window-jquery-load
16:47:32.052 ga.php available
there are two ways I know of for running non blocking js:
1- put your script tag before the closing tag of body
2- add 'async' attribute to the script, the end result will look like, note that this is for remote file inclusions:
<script src="script.js" async></script>
and the is the async you are finding in ga.aync=true, it prevents the blocking of the page rendering until the file is loaded, but it has no effect of what happens after the code is run, so, in other words, the created script tag (by running that code' allows the browser to do its job even while the file is being downloaded.
the code you provided, merely, creates a script tag to include ga.js before the first script tag in the page(which will be in the head normally).
so with that out of the way, the only option left is to run your script before the closing tag of the body, so that it runs after the page is parsed.
On another note, my advice to you is to learn about something called 'critical rendering path' of the browser, it explains why some stuff are blocking and best practices for using external files on your pages.
I hope this helped

jQuery works on jsFiddle but not in a live page

THE QUESTION
Interesting one that probably has a simple solution. With the help of #jessegavin I've added a jQuery function to my page that controls the playback of HTML5 audio elements on the page. The code is beautiful and works correctly on a jsFiddle, but not when put into the context of my page.
I've thrown time to the wind and methodically stepped through this to try and isolate my mistake, but with no avail. Really, I went Aristotle on this one and applied the scientific method. Please forgive me for the heft of this question. It's really my last resort.
THE NITTY GRITTY
Here are my findings: All the JavaScript functions for the page work correctly in context of the jsFiddle. After specifically adding the functions one at a time I can say that they each work appropriately, and that all except for the HTML5 audio playback work on both the jsFiddle and the live page. That is to say ONLY the HTML5 audio playback is not working on the live page.
All the HTML is 100% validated, all the CSS is 100% validated. Both groups are code are added into the jsFiddle in their entirety.
The page heading loads (in this order) an external CSS document, jQuery 1.5.1 and jQuery UI 1.8.8 (same on jsFiddle, except for UI, which is 1.8.9) via Google's onload command, an external JavaScript document (where ALL functions for the site reside), and finally a Google Analytics function.
The JavaScript is wrapped in a document ready framework.
My guess is that the discrepancy lies somewhere in the head, but I cant imagine what exactly it is. All the external links work correctly, evidenced by the JavaScript functions working correctly (except for the new audio controller).
THE POST SCRIPT
P.S.- Only works in Chrome and Safari as of yet.. The server I'm hosting the two audio files off of doesn't have the correct ht-access file declaring OGG as a correct MIME type. I'll start a question for that too.
RESOURCES
jsFiddle: http://jsfiddle.net/66FwR/3/
HTML (heading only, body is in jsFiddle)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<meta name="description" content="Fernando Garibay- Producer, Songwriter, Artist, Multi-Instrumentalist, and Programmer" />
<meta name="keywords" content="Fernando Garibay, Music, Producer, Songwriter, Artist, Mutli-Instrumentalist, Programmer." />
<title>Fernando Garibay - Music</title>
<link rel="icon" type="image/png" href="http://www.fernandogaribay.com/favicon.ico" />
<link href="../styles/fernando.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAqfg-jHFfaMB9PWES0K_8ChTCwkclEZER8BG2IP57SKkFV1O9hxSZkzKYPDs-3mbhEluKXjbKUAB7sQ"></script>
<script type="text/javascript">
  google.load("jquery", "1.5.1");
  google.load("jqueryui", "1.8.8");
</script>
<script type="text/javascript" src="../scripts/fernando.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-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>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<!--Copyright 2011, Fernando Garibay, Inc-->
<!--Developed by Minimal +-->
</head>
<body onload="message()">
JavaScript (the function that works on jsFiddle, but not in a live page)
$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio').get(0);
if (song.paused)
song.play();
else
song.pause();
});
});
I see two JavaScript errors on your live page (in both Chrome and Firefox):
Uncaught TypeError: Object [object Object] has no method 'fancybox'
Uncaught ReferenceError: message is not defined
You reference fancybox() in fernando.js, and message in the <body onload="message()">. Those errors are most likely stopping your audio control code from running.
The URL is http://fiddle.jshell.net/66FwR/3/show/ look at that.
It includes jQuery UI too. You could copy the source and use that.

View Asynchronous JavaScript calls

I've upgraded the tracking script for Google Analytics to the Asynchronous version. The only issue I have is being able to debug the calls. I was able to track the older version in Firebug using the approach outlined on this site, but now cannot view the gaq.push calls. Is there way to view this in Firebug or another tool?
This is my sample test page I'm trying to track:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Google Analytics Event Tracking</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-13250000-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>
<body>
Lorem ipsum dolor sit amet....<br />
<script type="text/javascript">
_gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);
</script>
</body>
</html>
I'm trying to confirm that "_gaq.push" is actually working.
I just ran into the same issue, and so I did a google search and ended up on this stack overflow question.. I too thought that this would just show up as a xhr request in firebug as that would be the simple way to track an event. Turns out they are using a 1x1 pixel gif to do the tracking! If you look in the Net > All tab in Firebug you will see a GET request made looking similar to this:
https://ssl.google-analytics.com/__utm.gif?utmwv=5.2.4&utms=28&utmn=1818843630&utmhn=dev-marketplace.asos.com&utmt=event&utme=5(my-home*sub-nav-click*blog-posts)&utmcs=UTF-8&utmsr=1920x1080&utmvp=1920x618&utmsc=24-bit&utmul=en-gb&utmje=0&utmfl=11.1%20r102&utmdt=Build%20%23%20Developer%20Live%20Feed%20ASOS%20Marketplace&utmhid=1950484512&utmr=-&utmp=%2Flivefeed%2Fblogposts&utmac=UA-23521416-1&utmcc=__utma%3D159014575.706813547.1328542287.1328542287.1328604985.2%3B%2B__utmz%3D159014575.1328542287.1.1.utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B&utmu=6AAAAAAAAAAAAAAAQ~
These are the params sent in the request
utmac UA-23521416-1
utmcc __utma=159014575.706813547.1328542287.1328542287.1328604985.2;+__utmz=159014575.1328542287.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
utmcs UTF-8
utmdt Build # Developer Live Feed ASOS Marketplace
utme 5(my-home*sub-nav-click*blog-posts)
utmfl 11.1 r102
utmhid 1950484512
utmhn dev-marketplace.asos.com
utmje 0
utmn 1818843630
utmp /livefeed/blogposts
utmr -
utms 28
utmsc 24-bit
utmsr 1920x1080
utmt event
utmu 6AAAAAAAAAAAAAAAQ~
utmul en-gb
utmvp 1920x618
utmwv 5.2.4
The TamperData plugin for Firefox is very handy. It lets you see all HTTP traffic, with filtering etc. It also has a facility that lets you modify headers before the browser starts the HTTP transaction, which seems pretty awesome but I've never used it.
I do this by looking at the Resources tab in Chrome Developer Tools:
http://drktd.com/45VJ (notice the yellow 'XHR' -- that means XMLHttpRequest, which is the kind of call you're likely looking for)
If you need an in-depth view of each request into/out of your system, you should really install Charles Proxy. It is the best of breed for this kind of stuff.
If you do not see the requests happening in FireBug, then they are not happening. Google Analytics is not somehow sidestepping the browser's ability to track what HTTP requests it is making, your code is simply not making them.

Google Analytics - Blocks HTML/page rendering

I have used the "Better Google Analytics JavaScript that doesn’t block page downloading" to load Google Analytics dynamically so that it will not block HTML / page rendering.
However, it appears occassionaly that my HTML page will block rendering on the Firefox 3.0 (WinXP) status message states:
"Transferring data from www.google-analytics.com"
Any ideas on how to load the Google Analytics JavaScript in a way in which it will not block HTML/page rending?
You could use Google Analytics [asynchronous loading of tracking codes][1]. The following snippet should help:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_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>
Put the Google Analytics code as the last thing before the </body> tag, like Google recommends?
You may be seeing this bug. Before 3.6, FF sometimes incorrectly blamed google analytics for slowing down the page...
https://bugzilla.mozilla.org/show_bug.cgi?id=487638
But it at the bottom (just before the </body>) and delay it:
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
if (typeof(_gat)=='object')
setTimeout(function(){
_gat._getTracker("UA-1234567-8")._trackPageview()}, 1500);
</script>
Have a look at my explanation about why I think this is the "best way to integrate analytics".
The DEFER attribute may work for you
<script DEFER type="text/javascript" src="http://www.google-analytics.com/ga.js">
<script DEFER type="text/javascript">... tracker code ...</script>

Categories