Javascript 在一页上有多个imageLoaded调用,并确保每个调用都已完成,然后再继续
我在我的页面上有3个部分,其中包含许多不同大小的图像,我需要做的是确保这3个部分中的每一个图像都已完全加载,然后再继续应用任何转换等,如淡入等 我想我知道我需要做什么,但我不确定是否执行它。我需要创建一个延迟对象,在完成解析延迟对象时监视每个调用,然后运行Javascript 在一页上有多个imageLoaded调用,并确保每个调用都已完成,然后再继续,javascript,jquery,jquery-deferred,Javascript,Jquery,Jquery Deferred,我在我的页面上有3个部分,其中包含许多不同大小的图像,我需要做的是确保这3个部分中的每一个图像都已完全加载,然后再继续应用任何转换等,如淡入等 我想我知道我需要做什么,但我不确定是否执行它。我需要创建一个延迟对象,在完成解析延迟对象时监视每个调用,然后运行deferred.when或deferred.done方法,这听起来像是正确的吗?就像我说的,我只是不知道该怎么做 我正在使用imagesLoaded插件,我的代码目前看起来如下: JS $(function () { va
deferred.when
或deferred.done
方法,这听起来像是正确的吗?就像我说的,我只是不知道该怎么做
我正在使用imagesLoaded插件,我的代码目前看起来如下:
JS
$(function () {
var def1 = $.Deferred();
var def2 = $.Deferred();
var def3 = $.Deferred();
var def = $.when(def1, def2, def3);
$('.set1').imagesLoaded(function () {
console.log('Set 1 ready');
def1.resolve();
});
$('.set2').imagesLoaded(function () {
console.log('Set 2 ready');
def2.resolve();
});
$('.set3').imagesLoaded(function () {
console.log('Set 3 ready');
def3.resolve();
});
def.done(function () {
console.log('ready');
});
});
JS小提琴
$.when()
函数是一个将多个延迟打包为一个延迟的实用程序。因为它返回自己的延迟,所以可以调用.done()
和fail()
并将其视为任何其他延迟
作为将来的参考,.then()
通常用于控制串行任务,$。when()
用于并行任务
loadImages()
函数是将loadImages
插件包装在一个文件中,以使其更通用
$(function () {
function loadImages(selector) {
var dfd = $.Deferred();
/*
...do work to load images...
if success, dfd.resolve()/dfd.resolveWith(...)
if failure, dfd.reject()/dfd.rejectWith(...)
to indicate progress, dfd.notify()/dfd.notifyWith(...)
*/
$(selector).imagesLoaded(function () {
var setResult = "dummy data";
dfd.resolve(setResult);
});
/*
If you return the dfd directly,
it can be canceled via .reject() from the outside.
To allow outside canceling just return the dfd.
*/
return dfd.promise();
}
//Run multiple deferreds in parallel and wait for all to complete with $.when
$.when(loadImages('.set1'), loadImages('.set2'), loadImages('.set3'))
.done(function(set1Result, set2Result, set3Result) {
//All resolved
})
.fail(function() {
//One or more failed
//If you want to know which one,
//you have to save a reference to each of
//the loadImages calls and determine through
//their individual .failure()'s
});
});