Google Analytics and the Retina Display

07-18-12 Andy Rossi

A quick and simple post with a helpful little script to track site visitors who have a high pixel density display — retina or otherwise.

Do you want to know how many visitors are viewing your site with a “retina” or similar high-density display? Well, do you use Google Analytics?

You do?! Excellent.

The solution is pretty simple. Here’s the gist.

// Create the test
var pixelRatio = (window.devicePixelRatio >= 1.5) ? "high" : "normal";
..

// Pass it along through GA
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);

// --- IMPORTANT LINE!
// params: event method, custom variable slot, variable name, variable value, scope level
// more info: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables
_gaq.push(['_setCustomVar', 1, 'Pixel Ratio', pixelRatio, 2 ]);

// Then start the trackin'
_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);
    })();

You can get to this information in your Google Analytics account through the Custom Variables area. Neat, eh? It may take a while to start collecting (up to an hour), but it will eventually appear.

Thanks to @chandlervdw for coming up with the problem to solve. Also, check out Rob Tarr’s article on Google Analytics and the resize event.