SoFunction
Updated on 2025-04-12

Javascript sample code to implement lazy image loading

No optimization examples

The following code is only used as an example to show you, not the internal code of the company.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img  src="https://img./20190808/v2_1565254363234_img_jpg">
    <img  src="https://img./20190905/v2_1567641293753_img_png">
    <img   src="https://img./20190905/v2_1567640518658_img_png">
    <img   src="https://img./20190905/v2_1567642423719_img_000">
    <img   src="https://img./20190905/v2_1567642425030_img_000">
    <img  src="https://img./20190905/v2_1567642425101_img_000">
    <img src="https://img./20190905/v2_1567642425061_img_000">
    <img  src="https://img./20190904/v2_1567591358070_img_jpg">
    <img  src="https://img./20190905/v2_1567641974410_img_000">
    <img  src="https://img./20190905/v2_1567641974454_img_000">
</body>
</html>

Load all images at once, which is not friendly to browser page loading.

The working mechanism of the browser

1. First understand the browser's running mechanism

When we visit a web page

  • Parsing HTML documents: Browser from the serverGet the HTML document and start parsingBuilding a DOM tree
  • Download style sheet: BrowserDownload CSS Stylesheet,andForm a CSS tree
  • Rendering page: The browser willCombining DOM tree and CSS treestand up,Generate rendering tree, and finally draw the visible page.
  • Processing scripts: If there are JavaScript scripts on the page, the browser will execute these scripts.

2. AlthoughJS is single threadedYes, butThe browser is multi-threadedof;imgTags andscriptTags will also allow the browser to start a new download thread to download pictures and JS files.Wait; if many pictures are loaded on the page at the same time, it will cause the browser to start a lotConcurrent tasks, increase the pressure on the browser; this is like going to the highway. If the traffic flow is too high,It is easy to cause congestion

Lazy loading

To implement lazy loading, we needManually control the loading of picturesThe process, rather than letting the browser automatically download all<img>Pictures in the tag.

1. Use data attributes

Store the actual image address indata-srcIn the properties

    <img  data-src="https://img./20190905/v2_1567641293753_img_png">
    <img   data-src="https://img./20190905/v2_1567640518658_img_png">

2. Listen to scroll events

        // Execute after DOM content is loaded        ('scroll', () =&gt; {
            // Call the loadImage function            loadImage();
        });

3. Implementation of functional functions

        // Define loadImage function        function loadImage() {
            // Get the visual area height of the document            let screenHeight = ;
 
            // Get the scroll bar position (compatible with different browsers)            let scrollTop =  || ;
 
            // traverse all pictures            for(let i = 0; i &lt; num; i++){
 
                // Check whether the current picture is in the viewing area                if(imgs[i].offsetTop&lt;screenHeight + scrollTop){
 
                    // Get the src attribute value of the image (using the data attribute)                    imgs[i].src = imgs[i].getAttribute('data-src');
 
                    // Update the currently loaded image index                    n = i + 1;
 
                    // Check whether all pictures that need to be lazy to load are loaded                    if (n === num){
                        // Stop listening to scroll events and perform performance optimization                        ('scroll', loadImage);
                    }
                }
            }
        }
  • clientHeightUsed to get the visible height of the element (excluding borders, inner margins and outer margins). This property is usually used to get the height of a window, document, or element, such as
  • scrollTopUsed to get or set the vertical scroll distance of an element relative to its scroll container. This value is the distance from the top of the element to the top of the viewport
  • offsetTopUsed to get the top offset of an element relative to the nearest positioned ancestor element. If there is no positioned ancestor, relative to the top of the document

Optimization: Lazy loading for anti-shake

Because the scrolling event is too sensitive, it is easy to trigger lazy loading functions at high frequencyloadImage, we can add one to itAnti-shakeOptimization operations to reduce the triggering of events.

Tool library

<script src="/ajax/libs//4.17.21/"></script>

Complete code

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Document&lt;/title&gt;
    &lt;script src="/ajax/libs//4.17.21/"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;img  data-price="20" data-src="https://img./20190808/v2_1565254363234_img_jpg"&gt;
    &lt;img  data-src="https://img./20190905/v2_1567641293753_img_png"&gt;
    &lt;img   data-src="https://img./20190905/v2_1567640518658_img_png"&gt;
    &lt;img   data-src="https://img./20190905/v2_1567642423719_img_000"&gt;
    &lt;img   data-src="https://img./20190905/v2_1567642425030_img_000"&gt;
    &lt;img  data-src="https://img./20190905/v2_1567642425101_img_000"&gt;
    &lt;img data-src="https://img./20190905/v2_1567642425061_img_000"&gt;
    &lt;img  data-src="https://img./20190904/v2_1567591358070_img_jpg"&gt;
    &lt;img  data-src="https://img./20190905/v2_1567641974410_img_000"&gt;
    &lt;img  data-src="https://img./20190905/v2_1567641974454_img_000"&gt;
    
    &lt;script&gt;
        // Get all img elements in the page        const imgs = ('img');
        // Get the number of img elements        const num = ;
        // Record which picture is currently loading, starting from 0        let n = 0;
 
        // When the DOM is fully loaded, execute the loadImage function        ('DOMContentLoaded', () =&gt; {
            loadImage();
        });
 
        // Define loadImage function        function loadImage() {
            ('121122');
            // Get the height of the visual area, compatible with different browsers            let screenHeight = ;
            // Get the scroll bar position, compatible with different browsers            let scrollTop =  || ;
 
            // traverse all pictures            for (let i = 0; i &lt; num; i++){
                // If the top position of the picture is in the viewing area                if (imgs[i].offsetTop &lt; screenHeight + scrollTop){
                    // Set the src attribute of the picture                    imgs[i].src = imgs[i].getAttribute('data-src');
                    // Update the loaded image index                    n = i + 1;
                    // If all pictures are loaded, remove the listener of the scroll event for performance optimization                    if (n === num){
                        // ('Loading completed');                        // After all pictures are loaded, remove the function function                        ('scroll', throttleLazyLoad);
                    }
                }
            }
        }
 
        // Use Lodash's throttle function to delay the execution of loadImage, reducing performance overhead        const throttleLazyLoad = _.throttle(loadImage, 300);
        // Add scroll event listener and execute throttleLazyLoad when scrolling        ('scroll', throttleLazyLoad);
        
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Summarize

Lazy image loading is a simple and effective front-end performance optimization technology. Everyone is welcome to discuss other better methods.

This is the article about Javascript's example code to implement lazy loading of images. For more related content related to Javascript's lazy loading of images, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!