文档准备好并加载图像后如何调用函数?
我正在使用这样的东西:
$(document).ready(function() {
$('#my-img').load(function() {
// do something
});
});
但有时它无法执行第二个回调(没有抛出任何错误,所以那里没有什么可做的),我想也许在文档准备好之前加载图像。
如果我不使用 $(document).ready() 部分,它就可以正常工作,所以我想我现在就保留这种方式。但有人告诉我,总是在文档准备好时进行回调是一个很好的做法,因为文档可能还没有准备好。是这样吗?
有什么想法吗?
I was using something like this:
$(document).ready(function() {
$('#my-img').load(function() {
// do something
});
});
But sometimes it fails to execute the second callback (without throwing any errors, so there's nothing to do there), and I'm thinking that maybe the image is being loaded before the document is ready.
If I don't use the $(document).ready() part, it works fine, so I think I'm gonna leave it that way for now. But someone told me that it was a good practice to always do this kind of thing as a callback on document ready, because the document might not be ready. Is that right?
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
摘自有关 load() 的文档
尤其是后者是一个常见问题。
您可以尝试 imagesLoaded 插件,但我使用以下方法运气更好:
它很脏,但是如果您确实需要在图像加载后执行某些操作,这是我能够开始工作的唯一可靠方法。
Taken from the documentation on load()
Especially the latter is a common problem.
You might try the imagesLoaded plugin, but I've had better luck with the following approach:
It's dirty, but if you really need to perform some action after the image has loaded this has been the only reliable approach I've been able to get to work.
老问题,但可能对谷歌用户有用:如果您需要在加载图像后执行代码,并且图像位于 DOM 中,则应该使用 $(window).load 而不是 $(document).ready。例如:
如果使用 SVG 或其他嵌入文档进行任何 jiggerypokery 操作,这一点至关重要。
Old question but may be useful to googlers: If you need code to execute after images are loaded, and the images are in the DOM, you should use $(window).load instead of $(document).ready. As in:
This is vital if doing any jiggerypokery with SVGs or other embedded documents.