JavaScript to implement the method of lazy loading plug-ins _javascript tips

Source: Internet
Author: User

Objective

Major forums on the web, especially on some types of pictures, in the picture load is a lazy load of the way, the specific performance, when the page is requested, only load the visual area of the picture, the other part of the picture is not loaded, only these pictures appear in the visual areas will dynamically load these pictures, Thus saving the network bandwidth and increasing the speed of the initial loading, the implementation of the technology is not complex, the following explained to it respectively.

The lazy loading of Web pictures is the mechanism for dynamically loading images by reading the IMG element and then getting the value of the IMG element data-src (which can also be contracted to other attribute names) and giving the IMG. src

the point to note here is that IMG does not set properties when initializing src , because even the settings src='' browser will try to load the picture.

A simple picture lazy load is involved in a total of two aspects

1. HTML conventions

We first need to add the specified here to the element that is ready to implement the lazy load, and assign the img class m-lazyload value to the property at the same time img src data-src .

The specific example is:

 
 

2. JavaScript implementation

Dynamic loading is divided into the following steps, where each step will be split into separate functions

1. Add page scrolling listener events

Window.addeventlistener (' scroll ', _delay, false);

function _delay () {
 cleartimeout (delay);
 Delay = settimeout (function () {
 _loadimage ();
 }, time);

2. The _loadimage function is executed when a listener event is triggered, which is responsible for loading the picture

function _loadimage () {for
 (var i = imglist.length; i--;) {
 var el = imglist[i];
 if (_isshow (EL)) {
  el.src = El.getattribute (' data-src ');
  El.classname = El.className.replace (New RegExp ("(\\s|^)" + _selector.substring (1, _selector.length) + "(\\s|$)"), ""); C15/>imglist.splice (i, 1);
 }}}

Although the function was executed _loadImage , but we have to know which pictures need to be loaded, what is the basis of judgment here?

The basis is to determine whether the picture is in the visual area of the current window, where we encapsulate a _isShow function to implement

function _isshow (EL) {
 var coords = El.getboundingclientrect ();
 Return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerheight | | document.d Ocumentelement.clientheight) + parseint (offset);
}

The closed loop, which is loaded from this image, forms a

When the page scrolling event is triggered-> perform the load picture operation-> Determine whether the picture is-> in the viewable area, the data-src values are dynamically assigned to the picture.

Is it too easy?

The truth is SO!!!

So simple, you might as well expand

Adding some custom parameters, everyone likes customizing, doesn't it?

Support iScroll , iScroll is a high-performance, less resource-intensive, non-reliant, multi-platform JavaScript scrolling plugin.

We've made some optimizations here.

Remove the selector after the picture has been loaded to avoid duplicate judgments.

Cache img element combination to reduce dom element query performance loss

Extended prototype Add getNode method that supports lazy loading of paging data (since we previously cached dom elements)

Ok! Say so much, show me the code bar!

(function () {var imglist = [],//Page all IMG element collection delay,//SetTimeout object offset,//offset, used to specify how far the picture is from the viewable area, load time,// Delay Loading time _selector;
 Selector defaults to. m-lazyload function _isshow (EL) {var coords = El.getboundingclientrect (); Return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerheight | | document.d
 Ocumentelement.clientheight) + parseint (offset)); function _loadimage () {for (var i = imglist.length; i--;)
  {var el = imglist[i];
  if (_isshow (EL)) {el.src = El.getattribute (' data-src ');
  El.classname = El.className.replace (New RegExp ("(\\s|^)" + _selector.substring (1, _selector.length) + "(\\s|$)"), "");
  Imglist.splice (i, 1);
 }} function _delay () {cleartimeout (delay);
 Delay = settimeout (function () {_loadimage ();
 }, time); function Imagelazyload (selector, options) {var defaults = Options | |
 {}; offset = Defaults.offset | |
 0; Time = Defaults.time | |
 250; _selector = Selector | |
 '. M-lazyload '; THis.getnode ();
  _delay ()//Avoid first loading of the not triggered touch event, actively triggering a load function if (defaults.iscroll) {defaults.iScroll.on (' scroll ', _delay);
 Defaults.iScroll.on (' Scrollend ', _delay);
 else {window.addeventlistener (' scroll ', _delay, false);
 } ImageLazyload.prototype.getNode = function () {imglist = [];
 var nodes = Document.queryselectorall (_selector);
 for (var i = 0, L = nodes.length i < l; i++) {Imglist.push (nodes[i));
}
 }; })();

Summarize

The above is the entire content of this article, I hope the content of this article for everyone to learn or use the picture lazy load can help, if there is doubt you can message exchange.

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.