1. What is lazy loading? When we visit a web page that displays a lot of pictures, the slow loading speed is often caused by the large number of pictures. A large number of img pictures cause page rendering to be blocked. By the time it takes a lot of effort to load all the images and pages, the user has already left. On the other hand, if the user only views the first part of the web page and then leaves, many images that have been loaded but are not presented in the viewport area because they are at the bottom of the web page will greatly increase the pressure on the server, but the user will not even see them, wasting performance. In order to solve the above problems, we need to introduce lazy loading of images. Lazy loading is actually very easy to understand. The key point is the word "lazy". When the user scrolls the corresponding visible area, if there are pictures in the visible area, they will be loaded. Pictures outside the visible area that have not been loaded will not be loaded first. If the user scrolls the visible area to them, they will be loaded. Otherwise, they will not be loaded at all. This greatly improves the performance of web page rendering and reduces unnecessary waste. 2. Implement lazy loading🌄:First, define a basic HTML page to simulate some web pages with a large number of images. For example, I use 8 img tags to simulate, and define some basic CSS styles. The code and initial effect are as follows: html: <img src="img/1.jpg" alt="xxx" /> <img src="img/2.jpg" alt="xxx" /> <img src="img/3.jpg" alt="xxx" /> <img src="img/4.jpg" alt="xxx" /> <img src="img/5.jpg" alt="xxx" /> <img src="img/6.jpg" alt="xxx" /> <img src="img/7.jpg" alt="xxx" /> <img src="img/8.jpg" alt="xxx" /> CSS: * { margin: 0; padding: 0; box-sizing: border-box; } img { width: 500px; height: 300px; object-fit: cover; margin: 20px; } body { display: flex; flex-wrap: wrap; justify-content: space-evenly; } The initial effect is as follows. You can see in the console on the right that all eight images are loaded and rendered when I run this page: Below are three ways to implement lazy loading using JavaScript. The principle is to determine whether the image appears in the visible area and then assign the src attribute to the image. 2.1 The first method:First, modify each img tag and use the data-attribute provided by HTML to embed custom data. We store the original image address of this tag in this custom data. At the same time, we use the same image to represent the src attribute of all images. This image can usually be an image that displays the words "loading". Note that if multiple img tag src reference the same image, it will only be loaded once and not multiple times, so I define the same image for each image src below. <img data-src="img/1.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/2.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/3.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/4.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/5.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/6.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/7.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/8.jpg" src="img/0.png" alt="xxx" /> The page effect is as follows: Next, we use JavaScript to load the image if it appears in the visible area when we scroll the scroll bar. Loading an image actually means assigning the original address to the src attribute of the img tag, then the image will be requested to be loaded and rendered. //Get all img tags var images = document.getElementsByTagName("img"); window.addEventListener("scroll", (e) => { //When a scroll event occurs, call the ergodic event ergodic(); }); function ergodic() { // Traverse each image for (let i of images) { //Judge whether the current image is in the visible area if (i.offsetTop <= window.innerHeight + window.scrollY) { //Get the value of the custom data-src attribute let trueSrc = i.getAttribute("data-src"); //Assign the value to the src attribute of the image i.setAttribute("src", trueSrc); } } } //Even if no scrolling event occurs, ergodic() must be executed once; Among them, offsetTop is the distance from the top of the element; window.innerHeight is the height of the current window; window.scrollY is the scroll distance; it is not difficult to know that when i.offsetTop <= window.innerHeight + window.scrollY, the image is in the visible area of ​​the window. The effect is as follows. Observe the console on the right and find that the image is loaded only when scrolling: 2.2 The second method:The second method is actually similar to the first one, except that the method of calculating whether the image is in the visible area is different, and the repeated parts are omitted, as follows: window.addEventListener("scroll", (e) => { ergodic(); }); function ergodic() { for (let i of images) { //The calculation method is different from the first method if (i.getBoundingClientRect().top < window.innerHeight) { let trueSrc = i.getAttribute("data-src"); i.setAttribute("src", trueSrc); } } } ergodic(); Among them, getBoundingClientRect().top is the position of the element relative to the window; window.innerHeight is the height of the current window; when the position of the element relative to the window is smaller than the height of the current window, it is naturally in the visible area of ​​the window. The effect is the same: 2.3 The third method (optimal):In fact, the above two methods have roughly realized lazy loading, but they both have a disadvantage, that is, when a scrolling event occurs, a large number of loops and judgment operations occur to determine whether the image is in the visible area. This is obviously not a good idea, so is there a solution? Here we introduce an observer interface called Intersection Observer, which is a constructor provided by the browser natively. Using it can save a lot of loops and judgments. Of course, its compatibility may not be very good, so use it according to the situation. What is Intersection Observer? The purpose of this constructor is to observe the intersection area between the visible window and the target element. Simply put, when we use it to observe our pictures, when the pictures appear or disappear in the visible window, it can know and execute a special callback function. We use this callback function to implement our operations. The concept is boring and difficult to understand, just look at the following example: 1. Since IntersectionObserver is a constructor provided by the browser natively, create a new instance first: const observer = new IntersectionObserver(callback); It will have a parameter callback, which is a callback function. It will be triggered once when the target element is visible, and will be triggered again when the target element is invisible. 2. Use the observer property to bind an observer to each image: for (let i of images) { observer.observe(i); } 3. From the above, we can know that each picture will trigger a callback function when it is visible and invisible. At the same time, the callback function also has a parameter entries. We can run the callback function to see what it is: function callback(entries) { console.log(entries) } It can be seen that the callback function is triggered every time the image is visible and invisible, and the content of the parameter entries is output. In fact, entries is an array, and its array elements are the target elements that have changed their status and triggered the event. There is an isIntersecting property which is true when the target element is visible in the viewport and false when it is not. We can use this attribute. When it is true, we set the src attribute value of the image that triggers this event to data-src and start loading it. function callback(entries) { for (let i of entries) { if (i.isIntersecting) { let img = i.target; let trueSrc = img.getAttribute("data-src"); img.setAttribute("src", trueSrc); } } } The target event attribute returns the element that triggered the event. Currently, when scrolling back, the image will be visible for a while and then invisible for a while, which triggers the callback function, so when a certain image has been loaded, we need to stop its observer. It can be stopped using the unobserve attribute. function callback(entries) { for (let i of entries) { if (i.isIntersecting) { let img = i.target; let trueSrc = img.getAttribute("data-src"); img.setAttribute("src", trueSrc); // End observation observer.unobserve(img); } } } Full code: var images = document.getElementsByTagName("img"); function callback(entries) { for (let i of entries) { if (i.isIntersecting) { let img = i.target; let trueSrc = img.getAttribute("data-src"); img.setAttribute("src", trueSrc); observer.unobserve(img); } } } const observer = new IntersectionObserver(callback); for (let i of images) { observer.observe(i); } The effect is as follows, lazy loading is achieved: 3. Summary:The above is all about implementing lazy loading of images. ✨In general, if some web pages with a large number of imgs load all the images during the page rendering phase, it will cause page rendering to be blocked. In order to solve the problem of lazy loading of images, the user scrolls the corresponding visible area, and if there is an image in the visible area, the image will be loaded. The core of this is to define a custom attribute data-src for the image to store the actual access address of the image. When the image appears in the visible area, the value of data-src is assigned to the src attribute, and the image is loaded at this time. Not only can the image position be determined by some common attributes, but the IntersectionObserver observer interface is also introduced to achieve lazy loading with less consumption. This concludes this article about the lazy loading of images (three methods) that is essential for the front end. For more related lazy loading of images, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Specific use of pthread_create in linux to create threads
>>: Detailed explanation of the problem of configuring servlet url-pattern in tomcat
1. parseFloat() function Make a simple calculator...
In higher versions of Tomcat, the default mode is...
Often when we open foreign websites, garbled char...
Note: It is recommended that the virtual machine ...
1. Time difference functions (TIMESTAMPDIFF, DATE...
I recently bought a Tencent Cloud server and buil...
1. Packetdrill compilation and installation Sourc...
TeamCenter12 enters the account password and clic...
ssh is one of the two command line tools I use mo...
Preface In the early stages of some projects, dev...
In an article a long time ago, I talked about the...
When we write pages, we sometimes find that the C...
1. Install dependency packages yum -y install gcc...
Use scenarios: The project's pages need to lo...
In front-end development, $ is a function in jQue...