1

I don't feel comfortable embedding an external JavaScript on my site to do all kinds of tracking that I don't actually need.

What I do need is referrer and screen size, which cannot be accomplished with a static HTML img tag alone.

What's the most standard-compliant, browser-supported and rendering-friendly way to load an invisible image, 1×1 gif, with a referrer and screen size as part of the URL?

I'm looking for a generic answer, although you could always phrase it in terms of the Google Analytics GIF Request Parameters.

cnst
  • 25,870
  • 6
  • 90
  • 122

1 Answers1

1

document.referrer will get you the referrer.

window.screen.width and window.screen.height will get you the screen resolution.

You can just use these with new Image() to have the browser request the tracking pixel. Use encodeURIComponent to sanitize the values before appending them to the URL.

var r = encodeURIComponent(document.referrer),
    x = window.screen.width,
    y = window.screen.height,
    img = new Image();
img.src = '/tracking.gif?x=' + x + '&y=' + y + '&r=' + r;

Note that on subsequent requests, this will be cached, so you won't get a count of pageviews (although you didn't say you wanted this). This could be desirable behavior since you'd get implicit unique visitor tracking. To circumvent caching, however, you could add something like the current timestamp via new Date().getTime(); as an additional parameter.

pauljz
  • 10,803
  • 4
  • 28
  • 33
  • Will `new Image()` cause rendering delays? – cnst May 14 '13 at 16:04
  • Nah, it shouldn't (although I suppose it would be browser dependent). People always used to use this method for pre-loading large images in the background, for example. – pauljz May 14 '13 at 16:06
  • so, it'll be loaded as an Image object, but not inserted anywhere into the actual rendering, just as one would want here? Are there any browsers that try to cheat here, and not load the object at all, until it's actually referenced? – cnst May 14 '13 at 16:09
  • Every browser I've seen will download the image when you do this. This is the same technique GA uses -- you never see a __utm.gif pixel in the DOM, for example. They actually use `new Image(1,1);` (and I'll admit I don't have a good answer as to why they specify the size like that). – pauljz May 14 '13 at 16:16