SoFunction
Updated on 2025-02-28

Summary of image lazy loading methods implemented by javascript (three methods)

When you see some large websites, if there are many pictures on the page, the picture in the current row will be loaded immediately when you scroll to the corresponding line. In this way, the page will only add images with visual areas when opening, while other hidden pictures will not be loaded. The program will speed up the page loading speed. For longer pages, this solution is better. The principle is as follows: the pictures below the visible area of ​​the page are not loaded first, and then load them when the user scrolls down to the image position. What are the benefits of doing this? ——When the page has several screens of content, it is possible that the user can only view the content of the first few screens, so that we can only load the pictures that the user needs to see, reducing the load generated by the server sending image files to the user's browser. The following are three methods to introduce to you the js to achieve delayed image loading.

JS implements image lazy loading method one:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
  <title></title> 
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  <meta http-equiv="description" content="this is my page"> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
  <!--<link rel="stylesheet" type="text/css" href="./" mce_href="">--> 
 </head> 
 <body style="text-align:center" mce_style="text-align:center"> 
 <p>  </p><p> </p><p> </p><p> </p><p> </p> 
  <div style="height:1290px;width:800px;border:1px;background:gray;"></div> 
  <div style="height:150px;width:800px;border:1px;background:green;"></div> 
  <img class="lazy" src="images/" mce_src="images/" alt="images/" /> 
  <script type="text/javascript"><!-- 
      var temp = -1;// Used to determine whether it is scrolling down (there is no need to judge whether the picture is delayed when scrolling up)       = function() { 
      var imgElements = ("img"); 
      var lazyImgArr = new Array(); 
      var j = 0; 
      for(var i=0; i<; i++) { 
       if(imgElements[i].className == "lazy"){ 
        lazyImgArr[j++] = imgElements[i]; 
       } 
      } 
              var scrollHeight = ;//The scrolling height      var bodyHeight = ;//Total height of visible area of ​​body (page)      if(temp < scrollHeight) {//To true means scrolling down, otherwise it is scrolling up and no action is required.       for(var k=0; k<; k++) { 
       var imgTop = lazyImgArr[k].offsetTop;//1305 (Picture vertical coordinate)       if((imgTop - scrollHeight) <= bodyHeight) { 
        lazyImgArr[k].src = lazyImgArr[k].alt; 
        lazyImgArr[k].className = "notlazy" 
               } 
      } 
      temp = scrollHeight; 
     } 
    }; 
// --></script> 
 </body> 
</html>

JS implements the delay loading method of web page pictures in two:

Before posting the code, let me tell you the principle of js to implement delayed image loading.

Implementation principle:

Change all pictures that need delay loading to the following format:

<img lazy_src="Picture Path" border="0"/>

Then when the page is loaded, all pictures that use lazy_src are saved to the array, and then the top of the visual area is calculated when scrolling, and then the src value of the picture with the top in the delayed loading is smaller than the current visual area (that is, the picture appears in the visual area) is replaced by lazy_src (load the picture):

JS code:

lazyLoad = (function() {
  var map_element = {};
  var element_obj = [];
  var download_count = 0;
  var last_offset = -1;
  var doc_body;
  var doc_element;
  var lazy_load_tag;
  function initVar(tags) {
    doc_body = ;
    doc_element =  == 'BackCompat' ? doc_body : ;
    lazy_load_tag = tags || ["img", "iframe"];
  };
  function initElementMap() {
    var all_element = [];
    //Find out all related elements that need delay loading    for (var i = 0,
len = lazy_load_tag.length; i < len; i++) {
      var el = (lazy_load_tag[i]);
      for (var j = 0,
len2 = ; j < len2; j++) {
        if (typeof (el[j]) == "object" && el[j].getAttribute("lazy_src")) {
          element_obj.push(all_element[key]);
        }
      }
    }
    for (var i = 0,
len = element_obj.length; i < len; i++) {
      var o_img = element_obj[i];
      var t_index = getAbsoluteTop(o_img); //Get the distance between the image relative to the document      if (map_element[t_index]) {
        map_element[t_index].push(i);
      } else {
        //Save a queue by distance        var t_array = [];
        t_array[0] = i;
        map_element[t_index] = t_array;
        download_count++; //The number of pictures that need delay loading      }
    }
  };
  function initDownloadListen() {
    if (!download_count) return;
    var offset = ( && !) ? doc_body.scrollTop : doc_element.scrollTop;
    //The visual area offset=the document's height+    var visio_offset = offset + doc_element.clientHeight;
    if (last_offset == visio_offset) {
      setTimeout(initDownloadListen, 200);
      return;
    }
    last_offset = visio_offset;
    var visio_height = doc_element.clientHeight;
    var img_show_height = visio_height + offset;
    for (var key in map_element) {
      if (img_show_height > key) {
        var t_o = map_element[key];
        var img_vl = t_o.length;
        for (var l = 0; l < img_vl; l++) {
          element_obj[t_o[l]].src = element_obj[t_o[l]].getAttribute("lazy_src");
        }
        delete map_element[key];
        download_count--;
      }
    }
    setTimeout(initDownloadListen, 200);
  };
  function getAbsoluteTop(element) {
    if ( != 1 || element == null) {
      return null;
    }
    var offsetTop = ;
    while (element = ) {
      offsetTop += ;
    }
    return offsetTop;
  }
  function init(tags) {
    initVar(tags);
    initElementMap();
    initDownloadListen();
  };
  return {
    init: init
  }
})();

How to use: Change the image src on the page that needs to be loaded in a delayed manner intolazy_src, then put the above js at the end of the body, and call:();
The teasing method can use firebug to see if the image is loading in a timely manner.

in addition:

If there is a column for switching content on your page, the pictures in the content that is switched during switching may not be displayed. The processing method is to load the image separately during content, such as:

/// Switch content code...("img[init_src]").each(function(){ 
  $(this).attr("src",$(this).attr("init_src")); 
  $(this).removeAttr("init_src"); 
 });

Original JS implements image delay loading method three:

 <!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>By nativejsDelay loading pictures</title>
<style type="text/css">
    div{width:100px;height:100px;background:#F00;margin-bottom:30px}
</style>
</head>
<body>
  <div><img data-url="/w/image/Sprites/PDW/
  " src="" /></div>
  <div><img data-url="/w/image/Sprites/PDW/
  " src="" /></div>
  <div><img data-url="/w/image/Sprites/PDW/
  " src="" /></div>
  <div><img data-url="/w/image/Sprites/PDW/
  " src="" /></div>
</body>
//You can copy multiple points when testing the above pictures<script type="text/javascript">
    (function(){
        //common
        function tagName(tagName){
            return (tagName);
        }
        function $(id){
            return (id);
        }
        function addEvent(obj,type,func){
            if(){
                (type,func,false);    
            }else if(){
                ('on'+type,func);
            }
        }
        // Here you can configure some parameters as needed        var v={
            eleGroup:null,
            eleTop:null,
            eleHeight:null,
            screenHeight:null,
            visibleHeight:null,
            scrollHeight:null,
            scrolloverHeight:null,
            limitHeight:null
        }
        //Initialize the data        function init(element){
            =tagName(element)
            screenHeight=;
            scrolloverHeight=;
            for(var i=0,j=;i<j;i++){
                if([i].offsetTop<=screenHeight && [i].getAttribute('data-url')){
                    [i].setAttribute('src',[i].getAttribute('data-url'));
                    [i].removeAttribute('data-url')
                }    
            }
        }
        function lazyLoad(){
            if( == 0){
                limitHeight=+;
            }else{
                limitHeight=+;
            }
            for(var i=0,j=;i<j;i++){
                if([i].offsetTop<=limitHeight && [i].getAttribute('data-url')){
                    [i].src=[i].getAttribute('data-url');
                    [i].removeAttribute('data-url')
                }    
            }
        }
        init('img')
        addEvent(window,'scroll',lazyLoad);
    })()         
</script>
</html>

The above content introduces the implementation of delayed image loading in js through three methods. I hope everyone likes it.