$(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
它很脏,但如果你真的需要在图像加载后执行一些动作,这是我能够开始工作的唯一可靠方法.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。