在执行某些操作之前要求 jQuery 等待所有图像加载的官方方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/544993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Official way to ask jQuery wait for all images to load before executing something
提问by Simon_Weaver
In jQuery when you do this:
在 jQuery 中,当你这样做时:
$(function() {
alert("DOM is loaded, but images not necessarily all loaded");
});
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.
它等待 DOM 加载并执行您的代码。如果未加载所有图像,则它仍会执行代码。如果我们正在初始化任何 DOM 内容,例如显示或隐藏元素或附加事件,这显然是我们想要的。
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?
假设我想要一些动画,并且在加载所有图像之前我不希望它运行。jQuery 中有官方的方法可以做到这一点吗?
The best way I have is to use <body onload="finished()">
, but I don't really want to do that unless I have to.
我拥有的最好方法是使用<body onload="finished()">
,但我真的不想这样做,除非我必须这样做。
Note: There is a bug in jQuery 1.3.1in 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.
注意:Internet Explorer中的 jQuery 1.3.1中存在一个错误,它实际上确实在执行内部代码之前等待所有图像加载完毕$function() { }
。因此,如果您使用该平台,您将获得我正在寻找的行为,而不是上述正确行为。
回答by paxdiablo
With jQuery, you use $(document).ready()
to execute something when the DOMis loaded and $(window).on("load", handler)
to execute something when all other things are loaded as well, such as the images.
使用 jQuery,您可以$(document).ready()
在加载DOM时执行某些内容,并在加载$(window).on("load", handler)
所有其他内容(例如图像)时执行某些内容。
The difference can be seen in the following complete HTML file, provided you have a jollyroger
JPEG files (or other suitable ones):
如果您有jollyroger
JPEG 文件(或其他合适的文件),则可以在以下完整的 HTML 文件中看到差异:
<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
? ? ? ? <img src="jollyroger99.jpg">
? ? </body>
</html>
With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:
这样,警报框就会在图像加载之前出现,因为此时 DOM 已准备就绪。如果你然后改变:
$(document).ready(function() {
into:
进入:
$(window).on("load", function() {
then the alert box doesn't appear until afterthe 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.
});
回答by alex
I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.
我写了一个插件,可以在图像加载到元素时触发回调,或者每个图像加载一次。
It is similar to $(window).load(function() { .. })
, except it lets you define any selector to check. If you only want to know when all images in #content
(for example) have loaded, this is the plugin for you.
它类似于$(window).load(function() { .. })
,但它允许您定义任何要检查的选择器。如果您只想知道#content
(例如)中的所有图像何时加载,这是适合您的插件。
It also supports loading of images referenced in the CSS, such as background-image
, list-style-image
, etc.
它还支持在CSS中引用图片,例如加载background-image
,list-style-image
等等。
waitForImages jQuery plugin
waitForImages jQuery 插件
Example Usage
示例用法
$('selector').waitForImages(function() {
alert('All images are loaded.');
});
More documentation is available on the GitHub page.
GitHub 页面上提供了更多文档。
回答by hyankov
$(window).load()
will work only the first time the page is loaded. If you are doing dynamic stuff (example: click button, wait for some new images to load), this won't work. To achieve that, you can use my plugin:
$(window).load()
只会在第一次加载页面时工作。如果您正在执行动态操作(例如:单击按钮,等待一些新图像加载),这将不起作用。为此,您可以使用我的插件:
/**
* Plugin which is applied on a list of img objects and calls
* the specified callback function, only when all of them are loaded (or errored).
* @author: H. Yankov (hristo.yankov at gmail dot com)
* @version: 1.0.0 (Feb/22/2010)
* http://yankov.us
*/
(function($) {
$.fn.batchImageLoad = function(options) {
var images = $(this);
var originalTotalImagesCount = images.size();
var totalImagesCount = originalTotalImagesCount;
var elementsLoaded = 0;
// Init
$.fn.batchImageLoad.defaults = {
loadingCompleteCallback: null,
imageLoadedCallback: null
}
var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
// Start
images.each(function() {
// The image has already been loaded (cached)
if ($(this)[0].complete) {
totalImagesCount--;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image is loading, so attach the listener
} else {
$(this).load(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// An image has been loaded
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
$(this).error(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image has errored
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
}
});
// There are no unloaded images
if (totalImagesCount <= 0)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);
回答by Dan Passaro
For those who want to be notified of download completion of a single image that gets requested after $(window).load
fires, you can use the image element's load
event.
对于那些希望在$(window).load
触发后收到请求的单个图像的下载完成通知的人,您可以使用图像元素的load
事件。
e.g.:
例如:
// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");
// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");
// wait for the image to load
$imgElement.load(function() {
alert("The image has loaded; width: " + $imgElement.width() + "px");
});
回答by Coz
None of the answers so far have given what seems to be the simplest solution.
到目前为止,没有一个答案给出了似乎是最简单的解决方案。
$('#image_id').load(
function () {
//code here
});
回答by Adrien Be
I would recommend using imagesLoaded.js
javascript library.
我建议使用imagesLoaded.js
javascript 库。
Why not use jQuery's $(window).load()
?
为什么不使用 jQuery 的$(window).load()
?
As ansered on https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951
It's a matter of scope. imagesLoaded allows you target a set of images, whereas
$(window).load()
targets all assets— including all images, objects, .js and .css files, and even iframes. Most likely, imagesLoaded will trigger sooner than$(window).load()
because it is targeting a smaller set of assets.
这是一个范围问题。imagesLoaded 允许您定位一组图像,而
$(window).load()
定位所有资产——包括所有图像、对象、.js 和 .css 文件,甚至 iframe。最有可能的是,imagesLoaded 会比$(window).load()
因为它针对的是较小的资产集而触发得更快。
Other good reasons to use imagesloaded
使用图像加载的其他充分理由
- officially supported by IE8+
- license: MIT License
- dependencies: none
- weight (minified & gzipped) : 7kb minified (light!)
- download builder (helps to cut weight) : no need, already tiny
- on Github : YES
- community & contributors : pretty big, 4000+ members, although only 13 contributors
- history & contributions : stable as relatively old (since 2010) but still active project
- IE8+官方支持
- 许可证:麻省理工学院许可证
- 依赖:无
- 重量(缩小和压缩):7kb 缩小(轻!)
- 下载生成器(有助于减轻重量):不需要,已经很小了
- 在 Github 上:是的
- 社区和贡献者:相当大,4000+ 成员,虽然只有 13 个贡献者
- 历史和贡献:稳定,相对较旧(自 2010 年以来)但仍然活跃的项目
Resources
资源
- Project on github: https://github.com/desandro/imagesloaded
- Official website: http://imagesloaded.desandro.com/
- Check if an image is loaded (no errors) in JavaScript
- https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
- imagesloaded javascript library: what is the browser & device support?
回答by molokoloco
With jQuery i come with this...
使用 jQuery 我带来了这个......
$(function() {
var $img = $('img'),
totalImg = $img.length;
var waitImgDone = function() {
totalImg--;
if (!totalImg) alert("Images loaded!");
};
$('img').each(function() {
$(this)
.load(waitImgDone)
.error(waitImgDone);
});
});
回答by Yevgeniy Afanasyev
Use imagesLoaded PACKAGED v3.1.8 (6.8 Kb when minimized). It is relatively old (since 2010) but still active project.
使用 imagesLoaded PACKAGED v3.1.8(最小化时为 6.8 Kb)。它相对较旧(自 2010 年以来),但仍然是活跃的项目。
You can find it on github: https://github.com/desandro/imagesloaded
你可以在 github 上找到它:https: //github.com/desandro/imagesloaded
Their official site: http://imagesloaded.desandro.com/
他们的官方网站:http: //imagesloaded.desandro.com/
Why it is better than using:
为什么它比使用更好:
$(window).load()
Because you may want to load images dynamically, like this: jsfiddle
因为你可能想动态加载图片,像这样:jsfiddle
$('#button').click(function(){
$('#image').attr('src', '...');
});
回答by Mario Medrano
This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.
通过这种方式,您可以在加载 body 或任何其他容器(取决于您的选择)中的所有图像时执行操作。纯 JQUERY,无需插件。
var counter = 0;
var size = $('img').length;
$("img").load(function() { // many or just one image(w) inside body or any other container
counter += 1;
counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
this.complete && $(this).load();
});
回答by Mariusz Charczuk
My solution is similar to molokoloco. Written as jQuery function:
我的解决方案类似于molokoloco。写成 jQuery 函数:
$.fn.waitForImages = function (callback) {
var $img = $('img', this),
totalImg = $img.length;
var waitImgLoad = function () {
totalImg--;
if (!totalImg) {
callback();
}
};
$img.each(function () {
if (this.complete) {
waitImgLoad();
}
})
$img.load(waitImgLoad)
.error(waitImgLoad);
};
example:
例子:
<div>
<img src="img1.png"/>
<img src="img2.png"/>
</div>
<script>
$('div').waitForImages(function () {
console.log('img loaded');
});
</script>