Home > Article > Web Front-end > How to implement lazy loading of images in JavaScript?
How to implement lazy loading of images in JavaScript?
With the development of mobile Internet, the number of pictures on web pages is increasing, which makes page loading speed slower and user experience degraded. In order to solve this problem, the image lazy loading function came into being. Lazy loading of images means that when the user scrolls to the image position, the image is loaded again to improve the loading speed of the web page. This article will introduce how to use JavaScript to implement lazy loading of images and provide specific code examples.
<img src="placeholder.jpg" data-src="image.jpg" alt="Lazy Load Image">
function lazyLoadImages() { var lazyImages = document.querySelectorAll('img[data-src]'); lazyImages.forEach(function(img) { if(isElementInViewport(img)) { img.src = img.getAttribute('data-src'); img.removeAttribute('data-src'); } }); } function isElementInViewport(el) { var rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth ); } window.addEventListener('scroll', lazyLoadImages); window.addEventListener('resize', lazyLoadImages);
scroll
and resize
events will be triggered. We can use these two events to Call the lazyLoadImages
function to determine and load images. lazyLoadImages
function immediately after the page is loaded to load the images in the visible area of the first screen. window.addEventListener('load', lazyLoadImages);
Through the above four steps, we can implement the lazy loading function of images. When the user scrolls to the image position, the image will automatically load, thereby improving page loading speed.
Summary:
Lazy loading of pictures is to store the real address of the picture in a specific attribute, and to judge whether the picture enters the visible area by listening to the events of page scrolling and window resizing, and based on the judgment results. Load images. This technology is particularly important on mobile devices and in environments with poor network performance, to improve user experience and reduce server load.
The above is an introduction to how JavaScript implements the lazy loading function of images, and provides corresponding code examples. Hope this helps!
The above is the detailed content of How to implement lazy loading of images in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!