Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

369
Vistas
How to check if an image path is valid in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda