我可以这样做吗?
(function (){function init(){
var imgload = new Image();
imgload.src = "/loading.gif";
imgload.onload = function(){
var img = new Image();
img.src = "/background.jpg";
img.src = "/logo.png";
img.src = "/newtab.png";
img.onload = function(){setTimeout(function() {
var html = document.getElementsByTagName("html")[0];
html.style.background = "url('/background.jpg') center center fixed";
html.style.backgroundRepeat = "repeat";
jQuery(".wrapper").fadeOut(400);
jQuery(".loading").fadeOut(300);
jQuery('.bodycontent').fadeIn(400)}, 300)}}}init()})();
我想设置多个.src,这样我就可以进行.onload直到加载.src中的图像。
这是一个好方法吗?
根据答案,这是我的操作方法:
function imgLoading(url) {
return new Promise(function(resolve) {
var img = new Image();
img.src = url;
img.onload = function() {
resolve(img);
}
});
}
let images =["/background.jpg","/logo.png","/submittrack.png", "/radio.png"];
var imgLoad = new Image();
imgLoad.src = "/loading.gif";
imgLoad.onload = function(){
let imageLoadPromises = images.map(imgLoading);
Promise.all(imageLoadPromises).then(function(images){
setTimeout(function() {
var html = document.getElementsByTagName("html")[0];
html.style.background = "url('/background.jpg') center center fixed";
html.style.backgroundRepeat = "repeat";
jQuery(".wrapper").fadeOut(400);
jQuery(".loading").fadeOut(300);
jQuery('.bodycontent').fadeIn(400)}, 300)
});
};
这是一个好方法
不会。src几乎会立即被覆盖,只有最后一个网址会在 onload
如果您需要知道何时加载所有图像,可以使用Promise
let images =["/background.jpg","/logo.png","/newtab.png"];
function imgLoad(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.src = url;
img.onload = function() {
resolve(img);
}
img.onerror = reject
});
}
// map an array of promises calling imgLoad() for each url
let imageLoadpromises = images.map(imgLoad);
Promise.all(imageLoadpromises ).then(function(images){
//images is array of image elements from above
// do something here , they have all loaded
}).catch(function(err){
console.log('One or more images did not load')
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句