如何在文件准备好和图像加载后调用函数? [英] How to call function after document ready AND image load?

查看:95
本文介绍了如何在文件准备好和图像加载后调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是这样的东西:

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.

如果我不使用$(文档).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?

有什么想法吗?

推荐答案

取自有关加载的文档()


与图像一起使用时加载事件的注意事项

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:

它不能一致地工作,也不能可靠地跨浏览器

It doesn't work consistently nor reliably cross-browser

它没有正确启动在WebKit中如果图像src设置为与之前相同的src

It doesn't fire correctly in WebKit if the image src is set to the same src as before

它没有正确地冒泡DOM树

It doesn't correctly bubble up the DOM tree

****对于已经存在于浏览器缓存中的图像,可以停止激活****

****Can cease to fire for images that already live in the browser's cache****

特别是后者是一个常见问题。

Especially the latter is a common problem.

您可以尝试 imagesLoaded插件,但我用以下方法运气更好:

You might try the imagesLoaded plugin, but I've had better luck with the following approach:

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

很脏,但是如果你真的需要在图像加载后执行一些操作,那么这是我能够开始工作的唯一可靠方法。

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.

这篇关于如何在文件准备好和图像加载后调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆