Michael Reston
Michael Reston

Reputation: 81

<img src> w/ timeout?

I have some tracking pixels on our site, that I'd like to protect against them impacting our user experience if their servers are down or slow. What's the easiest way to specify a maximum time the browser should attempt to load a given img - i.e. try for 100ms and then give up? (I'd rather not track a given customer than have a server hang on the third-party server impact our site).

Upvotes: 8

Views: 11014

Answers (5)

zswang
zswang

Reputation: 2320

as img.parentNode.removeChild(img)

Not all img have containers.

var img = new Image()
img.src = '...third-party server...'
setTimeout(function() {
  img.removeAttribute('src')
}, 100)

Upvotes: 0

Electro
Electro

Reputation: 3074

You could insert the <img> with JavaScript and use setTimeout() to remove it after 100ms.

Example with jQuery:

var tracker = $("<img>", { src: trackingUrl }).appendTo(document.body);
setTimeout(function() { tracker.remove(); }, 100);

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148544

you should load them when the document is ready. or at the lastline ( in the html). this way- it wont hurt the user experience. document ready can be also used with jQuery.

but you can use window.load.

as a rule(not always) - all scripts should be at the end of the page.

if you want to FORCE time out KILL :

create an img tag.

attach the load event to the img (this function will set flag : downloaded=1;)

set the src.

with setTimeout Function your gonna kill the img.

how ?

if after X MS the downloaded ==0 then kill.

so : each load event( from the IMg) is setting a flag ( downloaded=1).

your timeout function dont care about nothing!!! after x MS she going to kill the img - only if the downloaded==0.

Upvotes: 2

Cylindric
Cylindric

Reputation: 5894

You would have to use javascript to do this, there's nothing native to HTML/HTTP that would do this on a page basis. Google around for "HTML IMG timeout".

Upvotes: -1

ethrbunny
ethrbunny

Reputation: 10469

You could call a server process in the IMG tag. Let it worry about timing out the load.

Upvotes: -1

Related Questions