Lazy Loading is a common web performance optimization technique that delays the loading of non-critical resources on a page, such as images. When the user scrolls and the resources come into view, these resources begin to load. Here are several methods to implement lazy loading for images:
1. Using the native loading attribute (HTML5)
The latest HTML standard adds a loading attribute to the <img> tag, which can be set to lazy, causing the browser to automatically lazy load these images.
html<img src="example.jpg" loading="lazy" alt="description text" />
This method is the simplest and most direct, but it relies on browser support; older browsers may not support this attribute.
2. Implementing lazy loading with JavaScript
You can use JavaScript to listen for scroll events and dynamically load images. The basic approach is:
- Replace the
srcattribute of the image withdata-src, so the actual image is not loaded on initial load. - Listen for the page's scroll event.
- When the image enters the viewport, assign the value of
data-srctosrcto load the image.
Example code:
html<img data-src="example.jpg" alt="description text" />
javascriptdocument.addEventListener("DOMContentLoaded", function() { var lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"); let active = false; const lazyLoad = function() { if (active === false) { active = true; setTimeout(function() { lazyImages.forEach(function(lazyImage) { if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") { lazyImage.src = lazyImage.dataset.src; lazyImage.removeAttribute("data-src"); lazyImages = lazyImages.filter(function(image) { return image !== lazyImage; }); if (lazyImages.length === 0) { document.removeEventListener("scroll", lazyLoad); window.removeEventListener("resize", lazyLoad); window.removeEventListener("orientationchange", lazyLoad); } } }); active = false; }, 200); } }; document.addEventListener("scroll", lazyLoad); window.addEventListener("resize", lazyLoad); window.addEventListener("orientationchange", lazyLoad); });
3. Using the Intersection Observer API
This is a modern API that provides an asynchronous way to detect the intersection state of a target element with its ancestor elements or the top-level document's viewport.
javascriptdocument.addEventListener("DOMContentLoaded", function() { const lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"); const imageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { const image = entry.target; image.src = image.dataset.src; imageObserver.unobserve(image); } }); }); lazyImages.forEach(function(image) { imageObserver.observe(image); }); });
This method does not require listening for scroll events, offering better performance, but it requires browser support for Intersection Observer.
4. Using third-party libraries
There are also existing third-party libraries that can help implement lazy loading, such as lozad.js and lazysizes. These libraries typically provide more features and better compatibility.
html<script src="path_to_lazysizes.js" async=""></script> <!-- Use the class="lazyload" on img elements --> <img data-src="example.jpg" class="lazyload" alt="description text" />
When using third-party libraries, you typically only need to include the corresponding JavaScript file and make simple modifications to the image tags.