Javascript 我如何加载连续图像,直到有人发现';不存在?
我在几个目录中有许多图像,我希望能够加载特定目录中的所有图像。例如:Javascript 我如何加载连续图像,直到有人发现';不存在?,javascript,Javascript,我在几个目录中有许多图像,我希望能够加载特定目录中的所有图像。例如: directory-1 | ---- panel-1.png | |- panel-2.png | |- panel-3.png | directory-2 | ---- panel-1.png |- panel-2.png 我有很多这样的目录,每个目录中没有多少panel图像的模式 我想加载此目录中的所有图像 我的第一个方法是加载图像,直到出现404错误。然而,这似乎不起作用 const imagesLength =
directory-1
|
---- panel-1.png
| |- panel-2.png
| |- panel-3.png
|
directory-2
|
---- panel-1.png
|- panel-2.png
我有很多这样的目录,每个目录中没有多少panel
图像的模式
我想加载此目录中的所有图像
我的第一个方法是加载图像,直到出现404错误。然而,这似乎不起作用
const imagesLength = _(Array(15)).map((val, i) => {
const img = new Image
let valid = true
img.onerror = () => {
console.warn('error loading')
valid = false
return false
}
img.onload = () => {
if (_.includes(img, 'naturalHeight')) {
if (img.naturalHeight + img.naturalWidth === 0) {
console.log(img.naturalHeight, img.naturalWidth)
img.onerror()
valid = false
return false
}
} else if (img.width + img.height === 0) {
console.log(img.width, img.height)
img.onerror()
valid = false
return false
}
}
img.src = `/images/panel-${i+1}.png`
return valid // logic being, if valid is false it'll exit out of loop
}).compact().size() // I get 15
我不仅得到了错误数量的“有效”图像,我还得到了404个错误。我认为用onerror
处理错误应该可以抑制404个错误
我尝试过的其他事情:
- 尝试/抓住
- _.尝试
还有什么我能做的吗?我在这里为您制作了一把小提琴: 它应该给你一个实现你想要的选择的总体思路。基本上,我刚刚创建了一个递归回调函数,每次加载一个图像,直到达到404
var photos = document.getElementById('photos');
function loadImage(src, cb){
var img = new Image;
img.onload = function(){
photos.appendChild(img);
console.log('loaded image:', src);
cb();
};
img.onerror = function(err){
console.log('error:', err);
cb(err);
};
console.log('attempting to load image:', src);
img.src = src;
};
function loadSequential(pre, ext, first){
loadImage(pre + first + ext, function(err){
if(!err) { loadSequential(pre, ext, first + 1); }
});
}
loadSequential('http://www.mycitybynight.co.za/wp-content/uploads/2014/08/Tattoo-Mooiness-MyCityByNight-', '.jpg', 35);
注意:使用的照片是我找到的第一张顺序列表
至于404错误,我认为你无法避免这一点,因为你事先不知道你想要获得多少图像,而在页面出现之前,是浏览器处理这一点。但是,如果您控制服务器,则可以设置一个api,在您尝试下载特定文件之前检查该文件是否存在。如果您这样做了,那么我不明白您为什么不返回检索所需的实际图像列表,然后在客户端上打开确切的列表
这无疑是一个需要在服务器端更好地处理的问题。您是否有一些在线图像样本供我们使用?或者你能做一把小提琴吗?不会抑制404。。。onerror因为404而被抛出。必须向服务器发出请求,以了解该请求是否存在或不存在。谢谢你的澄清!我同意这肯定是服务器端的问题。然而,我只是想在不接触服务器的情况下快速制作一个原型。谢谢