JavaScript

Making a HTTP request before the page redirects

There are many ways to track when a user clicks on a link. It seems simple enough but there is something that people always forget and their code doesn't run. Let me show you an example.

<a id="link" href="external-link.html">Click me</a>

// JS
var link = document.getElementById("link");
link.onclick = function () {
    var img = new Image();
    img.src = "url/to/request";
};

There is only one problem. It takes time to make a HTTP request. When the user clicks, the img is created and the URL is requested, but right after the browser requests the anchor tag links. The image request is canceled and the anchor takes over.

There are two ways to fix this. One way is to use the onload event and run the code when the request is complete. The other way is just to request the second link after a delay.

// Method one
link.onclick = function () {
    var img = new Image(),
    url = this.href;
    img.onload = function() {
        window.location.href = url;
    };
    img.src = "url/to/request";

    return false; // cancel the link url
};

The only problem with this is the image has to be loaded first before the page redirects. The user can be left hanging, thinking the click was not registered. It can take time. But the next method always take the same amount of time.

// Method two
link.onclick = function () {
    var img = new Image(),
    url = this.href;
    img.src = "url/to/request";
    setTimeout(function() {
        window.location.href = url;
    },500); // run after 500 milliseconds

    return false; // cancel the link url
};

There you go. At this point, the request has enough time to reach the third party. We don't really care about the result that comes back. You can use this to trigger an event using google analytics for example.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only