jQuery alternative to bind('load') for use

2019-06-14 20:35发布

Possible Duplicate:
jQuery callback on image load (even when the image is cached)

So the .load() method has been deprecated in jQuery. load() is a shortcut for `bind('load', function).

From http://api.jquery.com/load-event/:

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`

How does one perform a function on image load consistently? My Current code looks like so:

$(newImage).bind('load', function() {
    createSlices(slide); 
});

However after reading the docs (although I haven't noticed any problems) I am worried it may not fire for some users.

4条回答
放荡不羁爱自由
2楼-- · 2019-06-14 20:50
var img = new Image();  
img.onload = function() {

} 

img.src=  src-image

the above code works on all browsers and even without jquery.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-14 20:59

There is a great library that handles exactly this: https://github.com/desandro/imagesloaded

I've used it in production and it works wonderfully. Extremely reliable, not a single complaint.

查看更多
Animai°情兽
4楼-- · 2019-06-14 21:14

You're right to worry, IE7/8 in particular will sometimes fail to fire the load event if the image is cached.

One technique is to immediately check if the image is complete after binding the load event:

$(newImage).bind('load error', function() {
    createSlices(slide); 
});

// check if the image is immediately complete (cached)
if (newImage.complete || typeof newImage.complete === 'undefined') {
    createSlices(slide);
}

I've tested with success in:

  • IE 7/8/9/10
  • FF4+
  • Chrome (latest)
  • Safari 5+
查看更多
别忘想泡老子
5楼-- · 2019-06-14 21:16

Try this plugin man: called waitforimages plugin: https://github.com/alexanderdickson/waitForImages (scroll down the link you will see various advanced use) - demo http://jsfiddle.net/FZ7Xy/

Hope it fits the need :)

Code

$('selector').waitForImages(function() {
    // All descendant images have loaded, now slide up.
    $(this).slideUp();  
});
查看更多
登录 后发表回答