Binding onload event on image object in jQuery

12,334

So few days ago I finally found out a solution to my problem..It seems its matter if I at first bind the onload event and then set the url of Image, or at first set the url and then bind the event.. Example

var photo = new Image();
photo.url = "http://www.something.com/something.jpg";
$(photo).bind('load',doSomething());


var photo = new Image();
$(photo).bind('load',doSomething());
photo.url = "http://www.something.com/something.jpg";

First variant runs usually ok, but sometimes it fails (in older IEs)..But the second variant is sure working propely..

Share:
12,334
simekadam
Author by

simekadam

Android developer at Avast Mobile.

Updated on June 04, 2022

Comments

  • simekadam
    simekadam almost 2 years

    I have following code on my site:

     backgroundImages[bg_img_path_b]=new Image();
     backgroundImages[bg_img_path_b].src =     bg_img_path_b;
     backgroundImages[bg_img_path_b].loaded="loading";
     //jQuery(backgroundImages[lastImage]).unbind('load.backgroundImages');                                         
    
     jQuery(backgroundImages[bg_img_path_b]).bind('load.backgroundImages',function(){
          if(typeof callback=='function'){
               callback.call(this, bg_img_path_b);
               if(showLoading) hideLoadingDC();
          }
     }).bind('load.cache', function(){
                                backgroundImages[bg_img_path_b].loaded="true";
                            });;
    

    There is large gallery for images used as background-images of page wrapper. I need to preload images because of speed (the images are quite large). So I have this code (actually is only a part of bigger function, which wraps caching and so on, but this few lines are fired when image is not in cache).

    backgroundImages is large array of Image objects, key is the path is the path of image. Every Image object has my property "loaded" which says if image has already been loaded, or is currently in state of loading.

    As you can see from my code I am calling callback function when the image is loaded (there are changes of the background etc.)

    But I have a problem with I.E<9, the callback is not successfully fired up (but not every time)..When I load my page for first it loads properly, but anytime I call this function again, it goes correctly through without errors, but the load event doesn't fired..

    I really don't know where could be an error, in all browsers except older IEs it works fine..

    Actually I need to debug if the event is bound correctly, but I can't see it in both IE and Chrome under load item in debugger:(

    Please help I am completely screwed, really don't know what to do.