<img loading="lazy"
does it without any Javascript
We are now getting more and more support for this standardized no-JavaScript method, which is very exciting!
You can see this at work in the code snippet below.
To see that the loading is actually lazy, open Chrome DevTools in the Network tab.
Then, as you scroll down the snippet, you will see that the images only load when you see them.
I've also added an optional JavaScript button to show that you can change lazy
back to the default eager
from JavaScript, and images will then start to load immediately.
document.getElementById('load-now').addEventListener('click', function(){
for (const img of document.getElementsByTagName('img')) {
img.loading = 'eager';
}
});
.separator {
height: 1000px;
width: 100px;
border: 5px solid red;
}
img {
height: 340px;
border: 5px solid black;
}
#load-now {
border: 5px solid black;
}
<div id="load-now">Click me to load all images now!</div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/5/56/Donald_Trump_official_portrait.jpg"></div>
<div class="separator"></div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/8/8d/President_Barack_Obama.jpg"></div>
<div class="separator"></div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/d/d4/George-W-Bush.jpeg"></div>
<div class="separator"></div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/d/d3/Bill_Clinton.jpg"></div>
<div class="separator"></div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/9/90/George_H._W._Bush%2C_President_of_the_United_States%2C_1989_official_portrait_%28cropped%29.jpg"></div>
<div class="separator"></div>
<div><img loading="lazy" height="340" src="https://upload.wikimedia.org/wikipedia/commons/1/16/Official_Portrait_of_President_Reagan_1981.jpg"></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…