George L. George L. - 24 days ago 10
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="https://ext.example.com/conversion/?c=122959&a=30225" width="1" height="1" onerror="this.onerror=null;this.src='https://a248.e.example.net/9e0d7c940412d5badab847b855f8ac46.com/conv/'+this.src.substring(this.src.indexOf('?'));" />`


Here is what i tried to do:

var lines = "<img src=";
var lines2="https://ext.example.com/conversion/?c=122959&a=30225";
var lines3=";this.src='https://a248.e.example.net/9e0d7c940412d5badab847b855f8ac46.com/conv/'+this.src.substring(this.src.indexOf('?'));";
setTimeout(function(){
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

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", "https://ext.example.com/conversion/?c=122959&a=30225");
    pixel.setAttribute("height", "1");
    pixel.setAttribute("width", "1");
    pixel.setAttribute("onerror", "this.onerror=null;this.src='https://a248.e.example.net/9e0d7c940412d5badab847b855f8ac46.com/conv/'+this.src.substring(this.src.indexOf('?'));");
    document.body.appendChild(pixel);
  }
  var timeout = setTimeout(addTrackingPixel, 10000);
};