使用jQuery .load()回调和图像

问题描述:

当使用jQuerys .load()方法动态地内容时,回调函数在请求完成并且HTML被拉到当前页面时触发。

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.

新HTML中包含的图像是否完全加载有什么办法?

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

谢谢!

据我所知,这不是直截了当的。有些可能建议使用 .load()事件处理程序,但Jquery文档有许多注意事项用于使用(文档):

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

开发人员尝试使用.load()
快捷方式解决的常见挑战是在图像(或
的集合)图像)已经完全加载。有几个已知的警告,
这个应该注意。这些是:

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:


  • 它的工作不一致也不可靠地跨浏览器

  • 如果图像src设置为与之前相同的src,则在WebKit中正常启动

  • 它没有正确地起泡DOM树

  • 可以对于已经在浏览器缓存中的图像停止触发

  • 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

是使用jQuery从您返回的HTML中拉出 img 元素,并使用javascript Image 对象加载图片。您可以 .onload 事件处理程序附加到 Image 对象。然后,您将需要跟踪何时使用延迟对象或甚至简单的计数器加载。

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.

这是一个演示,拉出 img 对象,并使用 $。Deferred()具有 $的对象when()在所有图像加载时触发:

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/

在演示中,内容只会在图像加载后加载。您将需要将 $。load()更改为 $。ajax()以使控件能够执行此操作。

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/