SoFunction
Updated on 2025-02-28

Implementation of lazy loading of js images

1. Usage scenarios

When there are a large number of images on the web page that need to be loaded, if all the images are loaded at once, the web page will be loaded too long;

The web page itself has been very slow to react. If you need to quote pictures on your page, it will also make things worse.

2. The principle of lazy image loading

Lazy loading of images is just a relatively high-quality name. The implementation method is very simple, which is to assign values ​​to the src attribute of the image when needed, that's all.

3. Code implementation

/**
  * Picture lazy loading
  */
function ImgLazyLoad() {
  /**
    * Scroll to the location of the image and load it
    * @param imgId
    * Lazy loading of the image ID
    * @param imgSrc
    * The address of the lazy image loading
    * @param distance
    * The visual distance of the picture (this parameter can be not passed)
    */
   = function(imgId,imgSrc,distance) {    
    // Get the src of the image    var img_source = $('#' + imgId).attr('src');
    // Only execute once    if("" == img_source) {
      // The visible height of the web page without scrolling      var documentClientHeight =  || ;
      // Get the distance from the top of the web page      var imgOffsetTop = $('#' + imgId)[0].offsetTop;
      // Get the visible height of the web page      // var bodyClientHeight = ;
      
      // 1. The height of the web page is less than the height of the visible area of ​​the web page (imgOffsetTop < documentClientHeight), and no scrolling event occurs      if (imgOffsetTop &lt; documentClientHeight) {
        $('#' + imgId)[0].src = imgSrc;
        return;
      }      
      
      // Get screen height      //var screenHeight = ;
      // The vertical offset distance from the upper left corner of the web page (distance from the top of the web page)      var max_imgClientTop = $('#' + imgId)[0].getBoundingClientRect().top;
      // There are decimals under ie, so only integers are taken      max_imgClientTop = parseInt(max_imgClientTop);
      // The visible distance of the picture (how much less you can see)      var max_imgClientDistance = max_imgClientTop - documentClientHeight;
      //0&lt;= distance &lt;=max_imgClientDistance
      // 1. When the parameter does not exist, set the value = 0; (When the picture just appears from the bottom of the visual area, the distance reaches the minimum) distance→→Min=0      // 2. Parameters > When the web page is visible, set the value = the height of the visible area; (When not scrolling, the distance reaches the maximum) distance→→Max=max_imgClientDistance, scrollTop=0      distance = ((distance || 0)&gt;max_imgClientDistance)?max_imgClientDistance:distance;
      
      // 2. No scrolling at maximum distance      if (distance == max_imgClientDistance) {
        $('#' + imgId)[0].src = imgSrc;
        return;
      }
      
      // Page binding scroll event      $(document).scroll(function(){
        
        // Get the web page rolled height        // var scrollTop =  || ;
        // Distance from the top of the web page        var imgClientTop = $('#' + imgId)[0].getBoundingClientRect().top;
        // The visual height of the picture        var clientHeight = documentClientHeight - imgClientTop;
        // The specified distance difference or the picture has entered the field of view        if (-clientHeight &lt;= distance || documentClientHeight &gt;= imgClientTop) {
          $('#' + imgId)[0].src = imgSrc;
        }
        
      });
    }
  };
  /**
    * Load by clicking another element
    * @param clickId
    * Page element ID of the bound click event
    * @param imgId
    *
    * @param imgSrc
    * The address of the lazy image loading
    */ 
  // 
   = function(clickId,imgId,imgSrc) {
    // Get the src of the image    var img_source = $('#' + imgId).attr('src');
    // Only execute once    if("" == img_source) {
      // Bind click event      $('#' + clickId).click(function(){
        $('#' + imgId)[0].src = imgSrc;
      });
    }
  };
};

Called:

$(function() {
  // Instantiate the object  var ill = new ImgLazyLoad();
  // Call  ('aa','/files/Marydon20170307/ws_products.bmp',404);
});

4. Involve knowledge points

There are also many implementation methods online, but the timing of loading pictures cannot be customized. In order to achieve this, it took a lot of effort to do it well.

The code is short, but there are many knowledge points involved.

// What is obtained is the height of the visible area of ​​the web page (without scrolling) || 
// What is obtained is the visible height of the web page (excluding the height of hidden elements)
// What you get is the height of the display
// Get the rolled height of the web page (the former is not supported under ie) || 
// Get the distance from the top of the web page (static dead value)('#id').offsetTop
('#id').getBoundingClientRect().top

The above is the detailed content of the implementation of lazy loading of js images. For more information about lazy loading of js images, please pay attention to my other related articles!