Reputation: 21
What I want to do:
I want to add all images within a specific folder into a List. The number of images within may vary between 1-10, but they are all named as numbers. The current way I am doing it is by first making all 10 of them and then removing the ones that don't exist.
List = []
for(var i=0; i<10; i++){
List.push('Folder/' + i+1 + 'jpg')
}
List = ['Folder/1.jpg', 'Folder/2.jpg', 'Folder/3.jpg'..]
Note: I am not going to host this anywhere. This is something I am making just for me. When I want to use the site I am just gonna open the index.html from the project folder.
I did some research and this seemed to work, but only while using live server in Visual Studio. This doesn't work when simply opening the index.html file locally.
function checkImage(){
temp_list = []
for(i=0; i<List.length; i++){
var http = new XMLHttpRequest();
http.open('HEAD', List[i], false);
http.send();
if(http.status != 404){
temp_list.push(List[i])
}
}
List= temp_list
I've also tried this, but it deletes everything in the List.
function checkImage(){
temp_list = []
for(i=0; i<List.length; i++){
checkImage2(List[i])
}
console.log(temp_list.length)
List= temp_list
}
function checkImage2(path){
var img = new Image();
img.onload = temp_list.push(path)
img.onerror = temp_list.splice(path,1)
img.src = path
}
My question: Is there a better way to check if a file(img) exists?
Upvotes: 0
Views: 1417
Reputation: 2787
You could use image.onerror
to check if image load correctly.
let images = ["invalid.jpg", "invalid2.jpg", "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png"]
let workedimages = images.slice()
images.forEach((item, index) => {
let img = new Image()
img.src = item
img.onerror = () => workedimages.splice(workedimages.indexOf(item), 1)
if (index == images.length - 1) {
img.onload = () =>
console.log(workedimages)
}
})
Upvotes: 2