Working with jQuery .load() callbacks and images

2020-06-28 12:59发布

When pulling in content dynamically with jQuerys .load() method, the callback function fires when the request is complete and the HTML is pulled through onto your current page.

Is there a way to work out when the images contained in the new HTML are fully loaded?

Thanks!

1条回答
放我归山
2楼-- · 2020-06-28 13:34

As far as I know, this is not straight-forward. Some may suggest using the .load() event handler, but Jquery documentation has a number of caveats for using that (documentation):

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

The only way that comes to mind is to use jQuery to pull the img elements out of your returned HTML, and use the javascript Image object to load the images. You can attach an .onload event handler to the Image object. You would then have to track when they are all loaded using something like a deferred object, or even a simple counter.

Here is a demo that pulls out img objects and uses $.Deferred() objects with a $.when() to trigger when all images are loaded:

http://jsfiddle.net/jtbowden/h4AMG/

In the demo, the content will only load after the images have loaded. You will need to change $.load() to $.ajax() to have the control to do this.

Here is a version that uses a basic counter to track loads:

http://jsfiddle.net/jtbowden/gnW3f/

查看更多
登录 后发表回答