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

266
Visualizações
Why doesn't adding loading="lazy" with JavaScript work to actually lazy load the images?

I'm able to add the loading="lazy" attribute on individual images, or with JavaScript and apply them all at once.

But, when I do it with JavaScript, and then inspect the page, I see the images load on page load, but each image has the attribute attached.

Why does adding loading="lazy" with HTML load the image lazily, but adding the attrib with JavaScript doesn't provide the lazy loading behavior?

let img = document.querySelectorAll('img');
for (let i = 0; i < img.length; i++) {
  let images = img[i];
  images.setAttribute('loading', 'lazy');
}
img {
  max-width: 100%;
  height: auto;
}

.container {
  margin-top: 2000px;
}
<div class="container">
  <img src="https://images.unsplash.com/photo-1481349518771-20055b2a7b24">
  <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b">
  <img src="https://images.unsplash.com/photo-1494232410401-ad00d5433cfa">
</div>

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

0

It's kind of a catch 22. You need to run the JS before the HTML to set the attribute before it is already loading, but you can't add an attribute to an element that doesn't exist.

You could try creating the image element manually using JS, then adding the attribute, then adding it to the dom.

Maybe something like this:

const imgEl = document.createElement("img");
imgEl.src = "https://i.stack.imgur.com/ZCVxN.jpg?s=64&g=1"
imgEl.setAttribute('loading', 'lazy');

const body = document.querySelector("body")
body.appendChild(imgEl);

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