在jQuery中绑定图片对象的onload事件

问题描述 投票:3回答:2

我的网站上有以下代码。

 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";
                        });;

有一个大的图片库,用来作为页面包装的背景图片。由于速度问题,我需要预加载图片(图片相当大)。所以我有这样的代码(实际上只是一个更大的函数的一部分,它包含了缓存等功能,但是这几行代码是在图片不在缓存中的时候启动的)。

backgroundImages 是一个大的Image对象数组,key是路径,是图片的路径。每个Image对象都有我的属性 "load",它表示图片是否已经被加载,或者当前处于加载状态。

从我的代码中你可以看到,当图像被加载时,我调用了回调函数(有背景的变化等)。

但是我在I.E<9上遇到了一个问题,回调函数并没有成功启动(但不是每次都启动)......当我第一次加载我的页面时,它加载得很正常,但是当我再次调用这个函数时,它没有出错,但是加载事件并没有启动。

我真的不知道是哪里出错了,在所有的浏览器中,除了老的IE,都能正常工作。

其实我需要调试事件是否正确绑定,但我在IE和Chrome浏览器的调试器中的加载项下都看不到:(

请大家帮帮我,我已经彻底完蛋了,真的不知道该怎么办。

javascript jquery onload jquery-events
2个回答
4
投票

几天前,我终于找到了解决问题的方法......似乎是先绑定onload事件,然后再设置Image的url,还是先设置url再绑定事件。

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";

第一个变量通常运行正常,但有时会失败(在旧IE中)......但第二个变量肯定工作得很好。


0
投票

你使用的是哪个jQuery API版本?试试使用最新版本的jQuery。

否则就用这个简单的JavaScript代码,在调用你的函数body on onload时加载图片。

var myimages = new Array();
var path = "images/gallery/";

function preloadimages() {
    for (i = 0; i < preloadimages.arguments.length; i++) {
        myimages[i]=new Image();
        myimages[i].src=path+preloadimages.arguments[i];
    }
}

// Enter name of images to be preloaded inside parenthesis with douable quotes. 
// Extend list as desired with comma.
preloadimages("gImg1.jpg","gImg2.jpg","gImg3.jpg","gImg4.jpg" /*, etc...*/);
© www.soinside.com 2019 - 2024. All rights reserved.