I'm working on a tracking function using the 1x1 pixel image trick, partially based on http://www.ebrueggeman.com/blog/redis-visitor-tracking.
My track.php looks like:
$out = date("Y-m-d H:i:s \n"); //later will pull and log data from $_SERVER
file_put_contents('log.txt', $out , FILE_APPEND );
//output appropiate headers and serve pixel
$pixel = '1x1.gif';
header('Content-Length: ' . filesize($pixel));
header('Content-Type: image/gif');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
print file_get_contents($pixel);
sleep(10); //<== for testing, to simulate possible extra processing or bottlenecks. Should NOT delay loading of main page
I've tried several ways of loading the image/script asynchronously:
//Option 1
//http://www.ebrueggeman.com/blog/redis-visitor-tracking
(function() { //console.log('s');
var pxl = document.createElement('img');
pxl.async = true;
pxl.src = 'track.php';
pxl.width = 1;
pxl.height = 1;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(pxl, s);
})();
//Option 2
var img = $("<img />").attr('src', 'track.php')
.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#here").append(img);
}
});
//Option 3
//https://github.com/sebarmeli/JAIL (Jquery Asynchronous Image Loader)
$(function(){
$('img.lazy').jail();
});
//Option4
$.ajax({
url: "track.php",
cache: false
});
When testing options 1 and 2, the browser keeps 'waiting' until the delay in track.php is completed. Should it do that? I tried both FF and Chrome and they keep turning, showing the page hasn't completely loaded yet.
On options 3 and 4 the page shows Ready immediately, but the code gets heavier by using external scripts and plugins.
What would be the best way of loading this script and giving the least possible delay and added processing to the page being tracked?
Thanks for any insight.
UPDATE:
I uploaded the test to a commercial hosting account, and it behaves as expected. Even when my local test was going through apache, for some reason the test behaved different when going through localhost. Thanks all for your input.
$(function() { });and$(document).ready(function()and it keeps delaying the page loading. Thanks for your help.$(document).load, see more here.$("<img />").attr('src', 'track.php').on('load', function() {...}).on('error', function() {...});with alerts to see whether load or error occurs.$(window).loadand Beetroot's suggestion and both keep the browser cursor turning until the delay is finished. The script is inside<head>. I'm testing the script onlocalhost(ubuntu). Not sure what else to try...