问题描述
在 jQuery 中执行此操作时:
In jQuery when you do this:
$(function() {
alert("DOM is loaded, but images not necessarily all loaded");
});
它等待 DOM 加载并执行您的代码.如果未加载所有图像,则它仍会执行代码.如果我们要初始化任何 DOM 内容,例如显示或隐藏元素或附加事件,这显然是我们想要的.
It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code. This is obviously what we want if we're initializing any DOM stuff such as showing or hiding elements or attaching events.
假设我想要一些动画,并且在加载所有图像之前我不希望它运行.jQuery 中有官方的方法可以做到这一点吗?
Let's say though that I want some animation and I don't want it running until all the images are loaded. Is there an official way in jQuery to do this?
我拥有的最好方法是使用 <body onload="finished()">
,但我真的不想这样做,除非我必须这样做.
The best way I have is to use <body onload="finished()">
, but I don't really want to do that unless I have to.
注意:有一个错误Internet Explorer 中的 jQuery 1.3.1,它实际上会在 $function() { }
中执行代码之前等待所有图像加载.因此,如果您使用该平台,您将获得我正在寻找的行为,而不是上述正确行为.
Note: There is a bug in jQuery 1.3.1 in Internet Explorer which actually does wait for all images to load before executing code inside $function() { }
. So if you're using that platform you'll get the behavior I'm looking for instead of the correct behavior described above.
推荐答案
使用 jQuery,您可以使用 $(document).ready()
在 DOM加载和 $(window).on("load", handler)
在加载所有其他内容(例如图像)时执行某些内容.
With jQuery, you use $(document).ready()
to execute something when the DOM is loaded and $(window).on("load", handler)
to execute something when all other things are loaded as well, such as the images.
如果您有很多 jollyrogerNN
JPEG 文件(或其他合适的文件),则可以在以下完整的 HTML 文件中看到差异:
The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN
JPEG files (or other suitable ones):
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert ("done");
});
</script>
</head><body>
Hello
<img src="jollyroger00.jpg">
<img src="jollyroger01.jpg">
// : 100 copies of this in total
<img src="jollyroger99.jpg">
</body>
</html>
这样,警报框就会在图像加载之前出现,因为此时 DOM 已准备就绪.如果您随后更改:
With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:
$(document).ready(function() {
进入:
$(window).on("load", function() {
然后警告框不会出现,直到之后加载图像.
then the alert box doesn't appear until after the images are loaded.
因此,要等到整个页面准备就绪,您可以使用以下内容:
Hence, to wait until the entire page is ready, you could use something like:
$(window).on("load", function() {
// weave your magic here.
});
这篇关于在执行某些操作之前要求 jQuery 等待所有图像加载的官方方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!