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:
xxxxxxxxxx
1
var images = document.querySelectorAll('img');
2
3
for (let image of images) {
4
image.loading = 'lazy';
5
}
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
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
5
<br>
6
<img src="https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png" />
7
<br>
8
<img src="https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png" />
9
<br>
10
<img src="https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png" />
11
<script>
12
13
var images = document.querySelectorAll('img');
14
15
for (let image of images) {
16
image.loading = 'lazy';
17
}
18
19
</script>
20
</body>
21
</html>