• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

149
Vistas
How to know when image preloading is done with javascript?

Per this extremely popular question, preloading images with javascript is as easy as:

function preloadImage(url) {
  var img=new Image();
  img.src=url;
}

But what I'd like to know is how can you know when that's done? I could just do a small setTimeout and assume it will be done after some small delay, but with varying connection speeds and especially for large images or large numbers of images this is unreliable.

Is there any way to actually know for sure when the loading is done?

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Image elements have two events that you can subscribe to to know that the image has loaded: onload and onerror:

function preloadImage(url, doneCallback) {
  var img=new Image();
  img.src=url;

  img.onload = () => {
    doneCallback();
  }

  img.onerror = () => {
    doneCallback(new Error('Failed to load image ' + url));
  }
}

preloadImage(url, (err) => {
  if (err) {
    console.log(err.message);
  }
  else {
    console.log('Preloading DONE!');
    // do what you want after preloading here!
  }
}

Or if you prefer Promises (so you can use async/await etc.):

function preloadImage(url) {
  var img=new Image();
  img.src=url;

  return new Promise((done, fail) => {
    img.onload = () => {
      done();
    }

    img.onerror = () => {
      fail(new Error('Failed to load image ' + url));
    }
  });
}

async function main () {
    console.log('preloading image!');

    await preloadImage(url);

    console.log('done preloading image!');
}

main().catch((err) => {
  console.log(err.message);
});
almost 3 years ago · Juan Pablo Isaza Denunciar

0

Just found the answer to my own question on the MDN docs for the Image class. There is a complete boolean attribute that tells you whether it's done.

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda