$(document).ready(function() { $('#my-img').load(function() { // do something }); });
但有时它无法执行第二次回调(没有抛出任何错误,所以没有什么可做的),我想也许图像是在文档准备好之前加载的.
如果我不使用$(document).ready()部分,它工作正常,所以我想我现在就要离开它了.但是有人告诉我,总是做这样的事情作为文件准备回调是一个好习惯,因为文档可能还没准备好.是对的吗?
有什么想法吗?
解决方法
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****
特别是后者是一个常见问题.
您可以试试imagesLoaded plugin,但我有更好的运气,采用以下方法:
var element = $('#my-img'); $("<img/>").load(function () { //create in memory image,and bind the load event //do something //var imageHeight = this.height; }).attr("src",element.attr("src")); //set the src of the in memory copy after binding the load event,to avoid WebKit issues