Home > Web Front-end > JS Tutorial > Summary of methods to implement lazy loading of images in javascript (three methods)_javascript skills

Summary of methods to implement lazy loading of images in javascript (three methods)_javascript skills

WBOY
Release: 2016-05-16 15:42:04
Original
1153 people have browsed it

I see some large websites. If the page has many pictures, when you scroll to the corresponding row, the pictures in the current row are loaded immediately. In this way, the page opens with only the pictures in the visible area, and Other hidden pictures will not be loaded, which will speed up page loading. For longer pages, this solution is better. The principle is this: the images below the visible area of ​​the page are not loaded until the user scrolls down to the image location, and then loaded. What are the benefits of doing this? ——When the page has several screens of content, it is possible that the user will only view the content of the first few screens. In this way, we can only load the images that the user needs to see and reduce the load caused by the server sending image files to the user's browser. Here are three steps: This method introduces to you js to implement delayed loading of images.

JS implementation of delayed image loading method 1:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
  <title>lazyImage2.html</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="./styles.css" mce_href="styles.css">--> 
 </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/sprite.gif" mce_src="images/sprite.gif" alt="images/lazyloadImg.jpg" /> 
  <script type="text/javascript"><!-- 
      var temp = -1;//用来判断是否是向下滚动(向上滚动就不需要判断延迟加载图片了) 
      window.onscroll = function() { 
      var imgElements = document.getElementsByTagName("img"); 
      var lazyImgArr = new Array(); 
      var j = 0; 
      for(var i=0; i<imgElements.length; i++) { 
       if(imgElements[i].className == "lazy"){ 
        lazyImgArr[j++] = imgElements[i]; 
       } 
      } 
              var scrollHeight = document.body.scrollTop;//滚动的高度 
      var bodyHeight = document.body.offsetHeight;//body(页面)可见区域的总高度 
      if(temp < scrollHeight) {//为true表示是向下滚动,否则是向上滚动,不需要执行动作。 
       for(var k=0; k<lazyImgArr.length; k++) { 
       var imgTop = lazyImgArr[k].offsetTop;//1305(图片纵坐标) 
       if((imgTop - scrollHeight) <= bodyHeight) { 
        lazyImgArr[k].src = lazyImgArr[k].alt; 
        lazyImgArr[k].className = "notlazy" 
               } 
      } 
      temp = scrollHeight; 
     } 
    }; 
// --></script> 
 </body> 
</html>
Copy after login

JS method to implement delayed loading of web page images:

Before I post the code, let me tell you the principle of js to implement delayed loading of images.

Implementation principle:

Change all images that need delayed loading to the following format:

<img lazy_src="图片路径" border="0"/>
Copy after login

Then when the page loads, save all the images using lazy_src into an array, then calculate the top of the visible area when scrolling, and then make the top of the delayed-loaded images smaller than the current visible area (i.e. the image The src value of the image appearing in the visible area is replaced with lazy_src (load the image):

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 = document.body;
    doc_element = document.compatMode == 'BackCompat' &#63; doc_body : document.documentElement;
    lazy_load_tag = tags || ["img", "iframe"];
  };
  function initElementMap() {
    var all_element = [];
    //从所有相关元素中找出需要延时加载的元素 
    for (var i = 0,
len = lazy_load_tag.length; i < len; i++) {
      var el = document.getElementsByTagName(lazy_load_tag[i]);
      for (var j = 0,
len2 = el.length; 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); //得到图片相对document的距上距离 
      if (map_element[t_index]) {
        map_element[t_index].push(i);
      } else {
        //按距上距离保存一个队列 
        var t_array = [];
        t_array[0] = i;
        map_element[t_index] = t_array;
        download_count++; //需要延时加载的图片数量 
      }
    }
  };
  function initDownloadListen() {
    if (!download_count) return;
    var offset = (window.MessageEvent && !document.getBoxObjectFor) &#63; doc_body.scrollTop : doc_element.scrollTop;
    //可视化区域的offtset=document的高+ 
    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 (arguments.length != 1 || element == null) {
      return null;
    }
    var offsetTop = element.offsetTop;
    while (element = element.offsetParent) {
      offsetTop += element.offsetTop;
    }
    return offsetTop;
  }
  function init(tags) {
    initVar(tags);
    initElementMap();
    initDownloadListen();
  };
  return {
    init: init
  }
})();
Copy after login

How to use: Change the src of the image that needs to be delayed loaded on the page to lazy_src, then put the above js at the end of the body, and then call: lazyLoad.init();
To tease, you can use firebug to check whether the image is delayed loading.

Also:

If there is a column with content switching on your page, the images in the content may not be displayed when switching. The solution is to load the images separately during the content, such as:

///切换内容的代码…
chlid.find("img[init_src]").each(function(){ 
  $(this).attr("src",$(this).attr("init_src")); 
  $(this).removeAttr("init_src"); 
 });
Copy after login

Original js implementation of image delayed loading method three:

 <!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>通过原生js延迟加载图片</title>
<style type="text/css">
    div{width:100px;height:100px;background:#F00;margin-bottom:30px}
</style>
</head>
<body>
  <div><img data-url="http://www.pokemon.name/w/image/Sprites/PDW/001.png
  " src="a.gif" /></div>
  <div><img data-url="http://www.pokemon.name/w/image/Sprites/PDW/002.png
  " src="a.gif" /></div>
  <div><img data-url="http://www.pokemon.name/w/image/Sprites/PDW/003.png
  " src="a.gif" /></div>
  <div><img data-url="http://www.pokemon.name/w/image/Sprites/PDW/004.png
  " src="a.gif" /></div>
</body>
//以上图片测试时可用复制多点
<script type="text/javascript">
    (function(){
        //common
        function tagName(tagName){
            return document.getElementsByTagName(tagName);
        }
        function $(id){
            return document.getElementById(id);
        }
        function addEvent(obj,type,func){
            if(obj.addEventListener){
                obj.addEventListener(type,func,false);    
            }else if(obj.attachEvent){
                obj.attachEvent('on'+type,func);
            }
        }
        //这里可以按照需要配置些参数
        var v={
            eleGroup:null,
            eleTop:null,
            eleHeight:null,
            screenHeight:null,
            visibleHeight:null,
            scrollHeight:null,
            scrolloverHeight:null,
            limitHeight:null
        }
        //对数据进行初始化
        function init(element){
            v.eleGroup=tagName(element)
            screenHeight=document.documentElement.clientHeight;
            scrolloverHeight=document.body.scrollTop;
            for(var i=0,j=v.eleGroup.length;i<j;i++){
                if(v.eleGroup[i].offsetTop<=screenHeight && v.eleGroup[i].getAttribute('data-url')){
                    v.eleGroup[i].setAttribute('src',v.eleGroup[i].getAttribute('data-url'));
                    v.eleGroup[i].removeAttribute('data-url')
                }    
            }
        }
        function lazyLoad(){
            if(document.body.scrollTop == 0){
                limitHeight=document.documentElement.scrollTop+document.documentElement.clientHeight;
            }else{
                limitHeight=document.body.scrollTop+document.documentElement.clientHeight;
            }
            for(var i=0,j=v.eleGroup.length;i<j;i++){
                if(v.eleGroup[i].offsetTop<=limitHeight && v.eleGroup[i].getAttribute('data-url')){
                    v.eleGroup[i].src=v.eleGroup[i].getAttribute('data-url');
                    v.eleGroup[i].removeAttribute('data-url')
                }    
            }
        }
        init('img')
        addEvent(window,'scroll',lazyLoad);
    })()         
</script>
</html>
Copy after login

The above content introduces js to implement delayed loading of images through three methods. I hope you like it.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template