本文概述
- 正确的方法如何起作用?
- 成功与错误的实现
正确的方法如何起作用?【如何验证何时在JavaScript中加载了多个图像】从理论上讲, 要验证何时加载所有图像, 你将需要具有一个用作计数器的标志变量。每当成功加载或未成功加载img时, 此计数器都会增加, 并且每次发生此事件时都需要触发另一个函数, 因此在过程结束时将执行yes或yes回调。此函数验证计数器值是否等于要加载的图像数, 并且在发生这种情况时将执行回调。你的回调将收到未加载的图像作为第一个参数:
// Create the flag variables (counter and total of images)var Counter = 0;
var TotalImages = 2;
// Create an instance of your imagesvar Image1 = new Image();
var Image2 = new Image();
// Store the images that were not correctly loaded inside an array to show latervar notLoadedImages = [];
// The onload callback is triggered everytime an image is loadedvar onloadCallback = function(){// Increment the counterCounter++;
// Verify if the counter is less than the number of imagesif(Counter <
TotalImages){return;
}// Trigger the final callback if is the last imgallLoadedCallback();
};
// The onerror callback is triggered everytime an image couldn't be loadedvar onerrorCallback = function(){// Increment the counterCounter++;
// Add the current image to the list of not loaded imagesnotLoadedImages.push(this);
// Verify if the counter is less than the number of imagesif(Counter <
TotalImages){return;
}// Trigger the final callback if is the last imgallLoadedCallback();
};
// The callback that is executed when all the images have been loaded or notvar allLoadedCallback = function(){console.log("Atention, the following images were not loaded ", notLoadedImages);
};
// Attach onload callbacksImage1.onload = onloadCallback;
Image2.onload = onloadCallback;
// Attach onerror callbacksImage1.onerror = onerrorCallback;
Image2.onerror = onerrorCallback;
// Load the images !Image1.src = "http://www.srcmini.com/queso.png";
Image2.src = "http://www.srcmini.com/image.jpg";
请注意, allLoadedCallback仅执行一次。显然, 代码只是逻辑工作方式的一个示例, 因此你可以包装它并使它与2个以上的图像一起工作。下一步显示了一个简单的函数, 该函数允许你使用一个函数加载多个图像, 并执行一个回调来通知是否加载了哪些图像。
成功与错误的实现以下ImageLoader方法以以下方式工作:你需要提供一个数组, 其中包含要加载的图像的URL作为第一个参数。在内部, 该函数将使用Image类加载它, 并循环访问图像的每个给定URL。当图像加载或不加载并存储在一个对象中时, 内部计数器将按照基本逻辑中的说明递增, 该对象将在稍后在onAllLoaded回调中返回:
注意由于浏览器是加载图像的浏览器, 因此你不必担心下载的性能, 因为图像肯定会被缓存, 并且可以随后用于在< img> 标签中呈现它们。
/** * Loader function that helps to trigger a callback when multiple images has been loaded. Besides * indicates which images were correctly/wrong loaded. * * @param {Array} Images An array of strings with the paths to the images. * @param {Function} Callback Callback function executed when all images has been loaded or not. */function ImageLoader(Images, Callback){// Keep the count of the verified imagesvar allLoaded = 0;
// The object that will be returned in the callbackvar _log = {success: [], error: []};
// Executed everytime an img is successfully or wrong loadedvar verifier = function(){allLoaded++;
// triggers the end callback when all images has been testedif(allLoaded == Images.length){Callback.call(undefined, _log);
}};
// Loop through all the images URLsfor (var index = 0;
index <
Images.length;
index++) {// Prevent that index has the same value by wrapping it inside an anonymous fn(function(i){// Image path providen in the array e.g image.pngvar imgSource = Images[i];
var img = new Image();
img.addEventListener("load", function(){_log.success.push(imgSource);
verifier();
}, false);
img.addEventListener("error", function(){_log.error.push(imgSource);
verifier();
}, false);
img.src = http://www.srcmini.com/imgSource;
})(index);
}}
然后可以这样使用:
ImageLoader(["example.png", "example.jpg", "http://i.imgur.com/fHyEMsl.jpg"], function(result){if(result.error){// outputs: ["example.png", "example.jpg"]console.log("The following images couldn't be properly loaded: ", result.error);
}// outputs: ["http://i.imgur.com/fHyEMsl.jpg"]console.log("The following images were succesfully loaded: ", result.success);
});
这种方法的优点是你将知道是否加载了哪些图像。请注意, 使用此功能, 你将能够验证到图像路径的字符串, 因为Image实例将不起作用(就像已经选择的img DOM元素一样, 因为不会触发onload回调)。
编码愉快!
推荐阅读
- JavaScript按位NOT,?运算符
- 画布已被跨源数据污染,污染的画布可能无法导出
- 使用“一键清理”功能要防止删除WORD文档
- 图解Web前端实现类似Excel的电子表格
- 配置思科路由器Telnet 登陆
- jquery.fileDownload.js插件导出excel
- Word中使用正则表达式进行查找和替换与难题征解
- Powershell 创建炫丽美观的Html报表
- Hadoop的word co-occurrence实现