Working with jQuery .load() callbacks and images

梦想与她 提交于 2019-12-05 07:12:09

问题


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:


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/



来源:https://stackoverflow.com/questions/10391762/working-with-jquery-load-callbacks-and-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!