Picture Lazy Loading Library echo.js source Learning

Source: Internet
Author: User

Not recently in the study of design patterns, and then saw the proxy mode loading pictures of the sample, and then realize their own, and found that their own write the goods can only load a picture at a time, and the picture to put in which is a very serious problem

Then went to Gayhub looked for the popular picture lazy loading library, this find, found a echo.j is, open a look, the source only more than 100 lines, shocked. , read the source, hey, Wood has on the agent mode Yes

Carefully study the next source: think this practice is more suitable for the picture location to determine the scene, such as article Ah, an article old long, there are quite a lot of pictures scattered in different places, it is more appropriate, there may be a lot of pictures readers will not turn to where, loading down on waste

Key points:

1. How to determine the length of the element distance in the field of view? Scroll down with a common mouse, as shown in the following illustration

          

Soul convey haha,,,; H1 is the height of the window,window.innerheight can be obtained, H2 is provided to the user set Offsetbottom

And a big trick! Element. getboundingclientrect (), you can get the four distance of the element relative to the window

            

var h=element.getboundingclientrect (). Top;var flag=h-(H1+H2);//When the flag value is less than 0, it means you can start loading the picture.

So, look at the source code inside how to write:

var = {///Four values are passed in by the user, the default is 0      t:,      B:,      L:,      r:};var   view = {/  /calculate the distance of the neighboring bounds      l:0-Offset.l,
   t:0-OFFSET.T,      B: (root.innerheight | | document.documentElement.clientHeight) + offset.b,      R: ( Root.innerwidth | | document.documentElement.clientWidth) + OFFSET.R}; var Ishidden = function (Element) {    return (element.offsetparent = = = null);  Element.offsetparent represents the parent element, if the null proof is not added to the DOM, or the position value is fixed  };    var InView = function (element, view) {  //Determines whether the function is called in the view to determine if    (Ishidden (Element)) {  //Determines whether the interface      return false;    }    var box = Element.getboundingclientrect ();  Calculates whether a four-sided distance satisfies the condition    return (box.right >= view.l && box.bottom >= view.t && box.left <= view.r &A mp;& box.top <= view.b);  };

  

2. Have the judgment function loaded, then how to do the lazy loading of the picture?

first load the loadding daisy picture, when the lazy loading conditions are met, switch the SRC attribute of IMG,

There are two more important values for the IMG element, one is SRC, one is Data-echo, (there is a background image, not too important, ignoring him) two, SRC set the address of a small chrysanthemum, data-echo the real address;

So what happens when all the page elements are set up like this?

When all the pictures are set to the same value SRC, that is, with the same Daisy diagram, after loading can be universal

The attribute of the IMG element is that when the SRC attribute is set, he will go to load this image first, if in JS immediately change the img src attribute, he would like to do a network request to load your JS set src address of the picture

but will first put the HTML inside the SRC picture is loaded, show, when you load the second picture when to replace, if you in the second picture when the load changed the SRC value,,, that is the same, what loading end when the display, Displays the original without loading

Source:

  if (InView (Elem, view)) {//whether the load condition is satisfied if (unload) {//If the settings are not loaded, save the daisy address in the Data-echo-placeholder attribute Elem.setat        Tribute (' Data-echo-placeholder ', elem.src); } if (Elem.getattribute (' data-echo-background ')!== null) {//img background picture elem.style.backgroundImage = ' url ('        + elem.getattribute (' data-echo-background ') + ') ';  }//When ele src is not equal to Data-echo value, that is, true steaming picture address, change the image of src else if (elem.src!== (src = elem.getattribute (' Data-echo ')))        {elem.src = src;          } if (!unload) {//If no settings are exceeded without loading, the properties can be cleared here Elem.removeattribute (' Data-echo ');        Elem.removeattribute (' Data-echo-background ');      } callback (Elem, ' load '); } else if (Unload &&!! (src = elem.getattribute (' Data-echo-placeholder '))) {//processing out of the picture is not loaded, the original saved small chrysanthemum map to the Elem src//Because the small chrysanthemum is the first loaded, so the picture switch back to the small chrysanthemum, no longer loaded before the real picture if set (Elem.getattribute (' data -echo-background ')!== null) {elem.style.backgroundImage = ' url (' + src +‘)‘;        } else {elem.src = src;         } elem.removeattribute (' Data-echo-placeholder ');      Callback (Elem, ' unload '); }} if (!length) {Echo.detach ();//Remove Event Listener}

  

3,scroll function Throttling

function throttling, two ways:

1: Will not be triggered when scrolling, the scroll will stop for a period of time to trigger

2: Trigger every other event

The first way, each time the scrolling process has been triggered, each time will be new to clear the last settimout, add a new Settimoutvar poll;function throttle () {  cleartimeout (poll); Poll=settimeout (function () {    echo.render ();},delay| | 250)}

  

  

VAR poll;
Function Throttle () {if (poll) { //exists settimout, does not clear, returns return directly ;} Cleartimout (poll); Poll=settimeout (function () { echo.render (); Poll=null; Allow the timer to be added again},delay| | 250)}

  

Picture Lazy Loading Library echo.js source Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.