Skip to content

Instantly share code, notes, and snippets.

@hatzopoulos
Last active April 22, 2019 10:23
Show Gist options
  • Save hatzopoulos/10664338 to your computer and use it in GitHub Desktop.
Save hatzopoulos/10664338 to your computer and use it in GitHub Desktop.
Optimized Google Universal Analytics
// Optimized Google Universal Analytics
// optional requirement 1:
// if using ga_track_pre_url feature;
// the DOM element must exist before document.getElementById('ga_track_pre_url').value
// like going just before the closing </body> tag
// optimized http://mathiasbynens.be/notes/async-analytics-snippet#universal-analytics
(function(G,o,O,g,l){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'),l=o.scripts[0];g.src='//www.google-analytics.com/analytics.js';l.parentNode.insertBefore(g,l)}(this,document,'ga'));
ga('create','UA-XXXXXXXX','auto');
// Enhanced Link Attribution:
// https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#enhancedlink
// https://support.google.com/analytics/answer/2558867?hl=en
ga('require','linkid', 'linkid.js');
// Support Display Advertising:
// https://support.google.com/analytics/answer/2444872?hl=en&utm_id=ad
ga('require','displayfeatures');
// Optionally Track special url, for example:
// if you were to set one for a redirect or goal
// <input type="hidden" name="ga_track_pre_url" value="//tracking/a/goal">
var u = document.getElementById('ga_track_pre_url').value;
if (u && u !='') ga('send','pageview', u);
// Send usual page view
ga('send','pageview');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment