Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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);
});
about 4 years ago · Juan Pablo Isaza Relatório

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda