JavaScript

Making fast cross-domain requests when the browser is leaving

There are times you want to make a very quick web request and don't care about the response looks like. It is possible to make requests using Ajax, but we still get a response.

One trick you will see many people are using is creating an image in JavaScript. The advantage of using an image is you are not limited to make requests on your own domain only. You can request your third party app if you wanted to.

Here is how it works:

function track(action,value) {
    var trackingUrl = "http://example.org/track?action="+
        encodeURLComponent(action)+ "value="+encodeURLComponent(value),
    img = new Image();
    img.src = trackingUrl;
}

We created an image and set the source property. There will be a response but we can safely ignore it. All we care about is that the request reaches it's destination. So we can track some user behavior using this function. For example, we can check how long the user has been on a page before leaving.

var startTime = (new Date()).getTime();

var links = document.getElementsByTagName("a"),
    i, l = links.length;

for (i = 0; i < l;i++){
    links[i].onclick = function () {
        var exitTime = (new Date()).getTime(),
        url = this.href;
        track("timeonsite",exitTime - startTime);
        setTimeout(function() {
            window.location.href = url;
        },500)
        return false;
    };
}

This little script will save the time when the page loads. When you click on a link, it makes a request to your tracking service and wait 500 milliseconds to give enough time for the request to initialize. Without getting a response it goes on to the link the user clicked.

500 millisecond is long enough for the request to go through and short enough for the user to not notice the delay.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only