0%

html-lazy-load-image

Introduction

How to implement lazy load images in html page?

Use loading=lazy attribute of img tag

With html5, you can use loading="lazy" attribute to lazy load images. This attribute tells the browser to defer loading of the image until it is needed. The browser will load the image when it is about to come into view.

1
<img src="image.jpg" loading="lazy" alt="描述性文字">

For old browsers which do not support loading attribute, you can use JavaScript to implement lazy load images.

1
2
<!-- HTML -->
<img data-src="image.jpg" class="lazyload" alt="描述性文字">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script>
document.addEventListener("DOMContentLoaded", function() {
let lazyImages = [].slice.call(document.querySelectorAll("img.lazyload"));

if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazyload");
lazyImageObserver.unobserve(lazyImage);
}
});
});

lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for browsers that do not support Intersection Observer
let oldLoad = function(imgs) {
imgs.forEach(function(img) {
img.src = img.dataset.src;
});
};
oldLoad(lazyImages);
}
});
</script>

Please note that, window.load event won’t wait for lazy loaded resources.

References

  1. https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading#images_and_iframes