Methods to implement lazy loading include: 1. Intersection Observer API; 2. Dynamic Import; 3. Custom event listeners, etc. Detailed introduction: 1. The Intersection Observer API is an API provided by the browser, which can be used to monitor the positional relationship between elements and the viewport. When the element enters the viewport, the API will trigger a callback function, in which the loading of resources can be executed. Operation; 2. Dynamic Import, etc.
The operating system for this tutorial: Windows 10 system, DELL G3 computer.
Lazy loading is a strategy to delay loading certain resources in web pages, such as images, videos, third-party scripts, etc. Through lazy loading, you can reduce the initial loading time of the page and improve the page loading speed and performance. Here are some common lazy loading methods.
1. Intersection Observer API
Intersection Observer API is an API provided by the browser, which can be used to monitor the positional relationship between elements and the viewport. When an element enters the viewport, the API triggers a callback function where the resource can be loaded. Here is an example of using the Intersection Observer API to implement lazy loading:
<img data-src="image1.jpg" class="lazy-load" /> <script> const lazyImages = document.querySelectorAll('.lazy-load'); const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.getAttribute('data-src'); observer.unobserve(img); } }); }); lazyImages.forEach(img => observer.observe(img)); </script>
In the above example, when the image element enters the viewport, the data-src attribute is replaced with the src attribute, and the image starts loading. When the image is loaded, the Intersection Observer API stops observing the element.
2. Dynamic Import
Dynamic Import is a module loading method introduced in ES6, which can dynamically load modules at runtime without preloading them in the