EN
JavaScript - set all existing images loading to lazy
0
points
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>