George L. George L. - 9 months ago 42
Javascript Question

How to load tracking pixel after 10 seconds?

My company wants to get some traffic from an Ads delivering agency, they gave us an Pixel tracking code and force us to load it on the website after 10 seconds.
I'm trying to do this through JS, but still fail.

Here is how the pixel looks:

`<img src="" width="1" height="1" onerror="this.onerror=null;this.src=''+this.src.substring(this.src.indexOf('?'));" />`

Here is what i tried to do:

var lines = "<img src=";
var lines2="";
var lines3=";this.src=''+this.src.substring(this.src.indexOf('?'));";
document.write(lines+'"'+lines2+'" width="1" height="1" onerror="this.onerror=null'+lines3+'" />');
}, 10000);

I use variables because of the --> ' <-- symbols

At the moment after 10 seconds all my contents disappear and the source code shows me only the Pixel code.

Do you have any less resource consuming solutions? How can i fire the Pixel on the webpage after 10 seconds

Answer Source

A pure JavaScript implementation that will append the tracking pixel to the <body> after 10 seconds.

window.onload = function() {
  function addTrackingPixel() {
    var pixel = document.createElement("IMG");
    pixel.setAttribute("src", "");
    pixel.setAttribute("height", "1");
    pixel.setAttribute("width", "1");
    pixel.setAttribute("onerror", "this.onerror=null;this.src=''+this.src.substring(this.src.indexOf('?'));");
  var timeout = setTimeout(addTrackingPixel, 10000);