这是一个将从数组中预加载图像并在最后一个完成时调用回调的函数:
function preloadImages(srcs, imgs, callback) { var img; var remaining = srcs.length; for (var i = 0; i < srcs.length; i++) { img = new Image(); img.onload = function() { --remaining; if (remaining <= 0) { callback(); } }; img.src = srcs[i]; imgs.push(img); }}// then to call it, you would use thisvar imageSrcs = ["src1", "src2", "src3", "src4"];var images = [];preloadImages(imageSrcs, images, myFunction);
而且由于我们现在处于使用诺言进行异步 *** 作的时代,因此以下是使用诺言并通过ES6标准诺言通知调用方的上述版本:
function preloadImages(srcs) { function loadImage(src) { return new Promise(function(resolve, reject) { var img = new Image(); img.onload = function() { resolve(img); }; img.onerror = img.onabort = function() { reject(src); }; img.src = src; }); } var promises = []; for (var i = 0; i < srcs.length; i++) { promises.push(loadImage(srcs[i])); } return Promise.all(promises);}preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) { // all images are loaded now and in the array imgs}, function(errImg) { // at least one image failed to load});
而且,这是使用2015 jQuery Promise的版本:
function preloadImages(srcs) { function loadImage(src) { return new $.Deferred(function(def) { var img = new Image(); img.onload = function() { def.resolve(img); }; img.onerror = img.onabort = function() { def.reject(src); }; img.src = src; }).promise(); } var promises = []; for (var i = 0; i < srcs.length; i++) { promises.push(loadImage(srcs[i])); } return $.when.apply($, promises).then(function() { // return results as a simple array rather than as separate arguments return Array.prototype.slice.call(arguments); });}preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) { // all images are loaded now and in the array imgs}, function(errImg) { // at least one image failed to load});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)