Skip to main content

To track traffic into and between their various properties, some websites use intermediate redirects to a page that does logging for all properties on a central standalone server. However, because such redirects always add latency between page transitions, it's good to avoid them and to find other ways of logging page views in the background.

# Track Web Traffic in the Background

To track traffic into and between their various properties, some websites use
intermediate redirects to a page that does logging for all properties on a
central standalone server. However, because such redirects always add latency
between page transitions, it's good to avoid them and to find other ways of
logging page views in the background. One popular way of recording page views
in an asynchronous fashion is to include a JavaScript snippet at the bottom of
the target page (or as an onload event handler), that notifies a logging
server when a user loads the page. The most common way of doing this is to
construct a request to the server for a "beacon", and encode all the data of
interest as parameters in the URL for the beacon resource. To keep the HTTP
response very small, a  transparent 1x1-pixel image is a good candidate for a
beacon request. A slightly more optimal beacon would use an HTTP 204 response
("no content") which is marginally smaller than a 1x1 GIF.

Here is a trivial example that assumes that www.example.com/logger is the
logging server, and that requests an image called beacon.gif. It passes the
URL of the current page and the URL of the referring page (if there is one) as
parameters:

	<script>
	 var thisPage = location.href;
	 var referringPage = (document.referrer) ? document.referrer : "none";
	 var beacon = new Image();
	 beacon.src = "http://www.example.com/logger/beacon.gif?page=" + encodeURI(thisPage)
	 + "&ref=" + encodeURI(referringPage);
	</script>

This type of beacon is best included at the very end of the page's HTML to avoid
competing with other HTTP requests that are actually needed to render the page
contents. In that way, the request is made while the user is viewing the page,
so no additional wait time is added.

#### Source

> [Make the Web Faster: Minimize round-trip times](https://developers.google.com/speed/docs/best-practices/)