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

118
Vistas
Async Javascript Promise to set src of img

EDIT: I'm still banging my head against my desk with this.

I'm trying to set the src for a bunch of img tags in a gallery, dynamically and with javascript. Each gallery slide has img tags which I have grouped into two categories, "before" and "after". The issue is that some pages have all 8 photos, but others have less. If an image loads successfully (*In this case let's define success as the response NOT being a 404 not found), a .loaded class is added to the img which gives it a border, but if there's a 404 not found, then a .hidden class is added, which sets display: hidden to the img.

Current problem: Despite some img tags generating the following error message in the console, "GET http://blablabla/Images/gallery/job1/before-1.jpg 404 (Not Found)", the .onerror doesn't fire, the .onload does. If I inspect the img tags (which are already on the page btw) that haven't loaded, I can see they have a filled out src attribute, although ofc an image at the provided path doesn't exist. Surely it should still be an error though?

const loadImg = function (img, url) {
    return new Promise((myResolve, myReject) => {
      img.src = url;
      img.onload = myResolve(img);
      img.onerror = myReject(img);
    });
  };

  const populateBeforeImgs = function () {
    for (let i = 0; i < beforeImgs.length; i++) {
      const img = beforeImgs[i];
      const url = `Images/gallery/job${galleryIndex}/before-${i + 1}.jpg`;
      loadImg(img, url)
        .then((value) => {
          value.classList.add("loaded");
        })
        .catch((error) => {
          error.classList.add("hidden");
        });
    }
  };

  const populateAfterImgs = function () {
    for (let i = 0; i < afterImgs.length; i++) {
      const img = afterImgs[i];
      const url = `Images/gallery/job${galleryIndex}/after-${i + 1}.jpg`;
      loadImg(img, url)
        .then((value) => {
          value.classList.add("loaded");
        })
        .catch((error) => {
          error.classList.add("hidden");
        });
    }
  };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is your loadImg function:

if (Response.ok) {       

Response is defined on window, but Response.ok is undefined. Undefined evaluates to false (is a falsy value)

Try this:

const loadImg = function(img, url) {
  return new Promise((resolve, reject) => {
    img.src = url;
    img.onload = () => resolve(img);
    img.onerror = () => reject(img);
  });
};

const img1 = new Image();
const img2 = new Image();

loadImg(img1, "https://www.placecage.com/c/200/300").then((img) => console.log("image 1 loaded!")).catch(() => console.warn("img 1 failed to load"));
loadImg(img2, "https://ihopethisisnotavalidurladasdasd").then((img) => console.log("image 2 loaded!")).catch(() => console.warn("img 2 failed to load"))

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