Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  16] [ 5]  / answers: 1 / hits: 42867  / 13 Years ago, fri, september 16, 2011, 12:00:00

I am looking for a way to implement this for as many browsers as possible:


var image = new Image();
image.addEventListener("load", function() {
alert("loaded");
}, false);
image.src = "image_url.jpg";

This didn't work in IE so I googled and found out that IE's lower than 9 do not support .addEventListener(). I know there is a jQuery equivalent called .bind() but that doesn't work on an Image(). What do I have to change for this to work in IE too?


More From » jquery

 Answers
14

IE supports attachEvent instead.



image.attachEvent(onload, function() {
// ...
});


With jQuery, you can just write



$(image).load(function() {
// ...
});


When it comes to events, if you have the possibility of using jQuery I would suggest using it because it will take care of browser compatibility. Your code will work on all major browser and you don't have to worry about that.



Note also that in order to the load event being fired in IE, you need to make sure the image won't be loaded from the cache, otherwise IE won't fire the load event.



To do this, you can append a dummy variable at the end of the url of your image, like this



image.setAttribute( 'src', image.getAttribute('src') + '?v=' + Math.random() );


Some known issues using the jQuery load method are




Caveats of the load event when used with images



A common challenge developers attempt to solve using the .load()
shortcut is to execute a function when an image (or collection of
images) have completely loaded. There are several known caveats with
this that should be noted. These are:




  • It doesn't work consistently nor reliably cross-browser

  • It doesn't fire correctly in WebKit if the image src is set to the
    same src as before

  • It doesn't correctly bubble up the DOM tree

  • Can cease to fire for images that already live in the browser's
    cache




See the jQuery docs for more info.


[#90070] Thursday, September 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazmyne

Total Points: 503
Total Questions: 102
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;