Languages
[Edit]
EN

JavaScript - set all existing images loading to lazy

0 points
Created by:
chelsea
806

In this article, we would like to show you how to set all existing images loading to lazy using JavaScript.

Quick solution:

var images = document.querySelectorAll('img');

for (let image of images) {
    image.loading = 'lazy';
}

 

Practical example

In this example, we select all img elements using the querySelectorAll() method. Then we iterate over them using for...of statement and set their loading attribute to lazy.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
  <br>
  <img src="https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png" />
  <br>
  <img src="https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png" />
  <br>
  <img src="https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png" />
  <script>

    var images = document.querySelectorAll('img');

    for (let image of images) {
        image.loading = 'lazy';
    }

  </script>
</body>
</html>

References

  1. Lazy loading - Web Performance | MDN
  2. Document.querySelectorAll() - Web APIs | MDN

Alternative titles

  1. JavaScript - set all existing img elements loading to lazy
  2. JavaScript - change all existing images loading to lazy
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join