gpt4 book ai didi

.onload 的 Javascript img 多个 .src

转载 作者:行者123 更新时间:2023-11-30 09:28:12 25 4
gpt4 key购买 nike

我可以这样做吗?

(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)

});
};

最佳答案

Is this a good approach

没有。 src 几乎会立即被覆盖,只有最后一个 url 会在 onload

中注册

如果您需要知道何时加载所有图像,您可以使用 promises

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')
});

关于.onload 的 Javascript img 多个 .src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com