Home  >  Article  >  Web Front-end  >  jQuery scrolling image implementation principle_jquery

jQuery scrolling image implementation principle_jquery

WBOY
WBOYOriginal
2016-05-16 15:25:581065browse

本文主要通过以下几方面来说明懒加载技术的原理,个人前端小菜,有错误请多多指出

一、什么是图片滚动加载?

  通俗的讲就是:当访问一个页面的时候,先把img元素或是其他元素的背景图片路径替换成一张大小为1*1px图片的路径(这样就只需请求一次),只有当图片出现在浏览器的可视区域内时,才设置图片正真的路径,让图片显示出来。这就是图片懒加载。

二、为什要使用这个技术?

  比如一个页面中有很多图片,如淘宝、京东首页等等,如果一上来就发送这么多请求,页面加载就会很漫长,如果js文件都放在了文档的底部,恰巧页面的头部又依赖这个js文件,那就不好办了。更为要命的是:一上来就发送百八十个请求,服务器可能就吃不消了(又不是只有一两个人在访问这个页面)。

  因此优点就很明显了:不仅可以减轻服务器的压力,而且可以让加载好的页面更快地呈现在用户面前(用户体验好)。

三、怎么实现?

关键点如下:

      1、页面中的img元素,如果没有src属性,浏览器就不会发出请求去下载图片(也就没有请求咯,也就提高性能咯),一旦通过javascript设置了图片路径,浏览器才会送请求。有点按需分配的意思,你不想看,就不给你看,你想看了就给你看~

  2、如何获取正真的路径,这个简单,现在正真的路径存在元素的“data-url”(这个名字起个自己认识好记的就行)属性里,要用的时候就取出来,再设置;

  3、开始比较之前,先了解一些基本的知识,比如说如何获取某个元素的尺寸大小、滚动条滚动距离及偏移位置距离; 

1)屏幕可视窗口大小:对应于图中1、2位置处

    原生方法:window.innerHeight 标准浏览器及IE9+ || document.documentElement.clientHeight 标准浏览器及低版本IE标准模式 || document.body.clientHeight 低版本混杂模式

       jQuery方法: $(window).height()

2)浏览器窗口顶部与文档顶部之间的距离,也就是滚动条滚动的距离:也就是图中3、4处对应的位置;

    原生方法:window.pagYoffset——IE9+及标准浏览器 || document.documentElement.scrollTop 兼容ie低版本的标准模式 || document.body.scrollTop 兼容混杂模式;

        jQuery方法:$(document).scrollTop();

3)获取元素的尺寸:对应于图中5、6位置处;左边jquery方法,右边原生方法

    $(o).width() = o.style.width;

    $(o).innerWidth() = o.style.width+o.style.padding;

    $(o).outerWidth() = o.offsetWidth = o.style.width+o.style.padding+o.style.border;

    $(o).outerWidth(true) = o.style.width+o.style.padding+o.style.border+o.style.margin;

注意:要使用原生的style.xxx方法获取属性,这个元素必须已经有内嵌的样式,如e31ba3b7ffde9fe45d1f89b68338313416b28748ea4df4d9c2150843fecfba68;

If the css style was originally defined through an external or internal style sheet, you must use o.currentStyle[xxx] ||document.defaultView.getComputedStyle(0)[xxx] to obtain the style value

4) Get the position information of the element: corresponds to positions 7 and 8 in the picture

1) Returns the distance of the element relative to the top and left side of the document;

jQuery: The distance between the $(o).offset().top element and the top of the document, and the distance between the $(o).offset().left element and the left edge of the document

Native: getoffsetTop(), there are specific instructions on the elevation, so I will ignore it here;

By the way, the offset distance of the returned element relative to the first positioned parent element, pay attention to the difference from the offset distance above;

jQuery: position() returns an object, $(o).position().left = style.left, $(o).position().top = style.top;

4. After knowing how to obtain the element size and offset distance, the next question is: How to determine whether an element has entered or is about to enter the visual window area? The following is also a picture to illustrate the problem.

1) The largest box outside is the actual page size, the light blue box in the middle represents the size of the parent element, objects 1~8 represent the actual position of the element on the page; the following instructions are done in the horizontal direction!

 2) The offset distance (offsetLeft) of the left border of object 8 relative to the left border of the page is greater than the distance of the right border of the parent element relative to the left border of the page. At this time, the element can be read outside the parent element;

 3) The left border of object 7 crosses the right border of the parent element. At this time: the offset distance (offsetLeft) of the left border of object 7 relative to the left border of the page is less than the distance of the right border of the parent element relative to the left border of the page, so Object 7 enters the visible area of ​​the parent element;

 4) At the position of object 6, the distance between the right edge of object 5 and the left edge of the page is greater than the distance between the left edge of the parent element and the left edge of the page;

5) When at the position of object 5, the distance between the right edge of object 5 and the left edge of the page is less than the distance between the left edge of the parent element and the left edge of the page; at this time, it can be judged that the element is outside the visible area of ​​the parent element;

6) Therefore, two conditions must be met in the horizontal direction to indicate that the element is within the visible area of ​​the parent element; similarly, the two conditions must be met in the vertical direction; see the source code below for details;

4. Expand to jquery plug-in
Usage: $("selector").scrollLoad({ parameters are explained in the code })

(function($) {
 $.fn.scrollLoading = function(options) {
  var defaults = {
   // 在html标签中存放的属性名称;
   attr: "data-url",
   // 父元素默认为window
   container: window,
   callback: $.noop
  };
  // 不管有没有传入参数,先合并再说;
  var params = $.extend({}, defaults, options || {});
  // 把父元素转为jquery对象;
  var container = $(params.container);
  // 新建一个数组,然后调用each方法,用于存储每个dom对象相关的数据;
  params.cache = [];
  $(this).each(function() {
   // 取出jquery对象中每个dom对象的节点类型,取出每个dom对象上设置的图片路径
   var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
   //重组,把每个dom对象上的属性存为一个对象;
   var data = {
    obj: $(this),
    tag: node,
    url: url
   };
   // 把这个对象加到一个数组中;
   params.cache.push(data);
  });

  var callback = function(call) {
   if ($.isFunction(params.callback)) {
    params.callback.call(call);
   }
  };
  
  //每次触发滚动事件时,对每个dom元素与container元素进行位置判断,如果满足条件,就把路径赋予这个dom元素!
  var loading = function() {
   // 获取父元素的高度
   var contHeight = container.outerHeight();
   var contWidth = container.outerWidth();

   // 获取父元素相对于文档页顶部的距离,这边要注意了,分为以下两种情况;
   if (container.get(0) === window) {
    // 第一种情况父元素为window,获取浏览器滚动条已滚动的距离;$(window)没有offset()方法;
    var contop = $(window).scrollTop();
    var conleft = $(window).scrollLeft();
   } else {
    // 第二种情况父元素为非window元素,获取它的滚动条滚动的距离;
    var contop = container.offset().top;
    var conleft = container.offset().left;
   }

   $.each(params.cache, function(i, data) {
    var o = data.obj, tag = data.tag, url = data.url, post, posb, posl, posr;
    if (o) {
     //对象顶部与文档顶部之间的距离,如果它小于父元素底部与文档顶部的距离,则说明垂直方向上已经进入可视区域了;
     post = o.offset().top - (contop + contHeight);
     //对象底部与文档顶部之间的距离,如果它大于父元素顶部与文档顶部的距离,则说明垂直方向上已经进入可视区域了;
     posb = o.offset().top + o.height() - contop;

     // 水平方向上同理;
     posl = o.offset().left - (conleft + contWidth);
     posr = o.offset().left + o.width() - conleft;

     // 只有当这个对象是可视的,并且这四个条件都满足时,才能给这个对象赋予图片路径;
     if ( o.is(':visible') && (post < 0 && posb > 0) && (posl < 0 && posr > 0) ) {
      if (url) {
       //在浏览器窗口内
       if (tag === "img") {
        //设置图片src
        callback(o.attr("src", url));
       } else {
        // 设置除img之外元素的背景url
        callback(o.css("background-image", "url("+ url +")"));
       }
      } else {
       // 无地址,直接触发回调
       callback(o);
      }
      // 给对象设置完图片路径之后,把params.cache中的对象给清除掉;对象再进入可视区,就不再进行重复设置了;
      data.obj = null;
     }
    }
   });
  };
  //加载完毕即执行
  loading();
  //滚动执行
  container.bind("scroll", loading);
 };
})(jQuery);

The above is a detailed introduction to the implementation principle of scrolling loading images. I hope it will be helpful to everyone's learning.

Statement:
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