A picture delay-loading plug-in with jquery (with picture delay loading principle) _jquery

Source: Internet
Author: User

Delayed loading of pictures is also called lazy loading, which is usually applied to pages with more pictures. If a page picture is more, and the page height or width has several screens, the page first load, only show the picture of the visual area, when the page scrolling, the picture into the visual area to load, which can significantly improve the loading speed of the page , fewer pictures concurrent requests can also reduce the pressure on the server. If the user only stays in the first screen, can also save traffic. If you have more pictures in the tab, you can also apply it to the tab and then load the picture when the tab is triggered.

Picture delay loading principle is relatively simple, first the real address of the picture is cached in a custom attribute (LAZY-SRC), and the SRC address using a 1x1 full transparent placeholder image to replace, of course, placeholder picture can also be other pictures.

Copy Code code as follows:

Because JavaScript is used to load pictures, if the user disables JavaScript, you can set an alternative scheme.

Copy Code code as follows:

<noscript></noscript>

When the page is first loaded, get the picture's position in the page and cache (the value of each offset will cause the page to reflow), calculate the visible area, when the picture position appears in the visible area, the SRC value is replaced with the real address, at this time the picture starts to load.

When the page scrolls, then determine whether the image has been cached location values in the visual area, to replace SRC load. When all the pictures have been loaded, unload the corresponding triggering events to avoid the memory leaks caused by repetitive operations. The whole window is considered a large container, you can also set a small container in the page, in the small container can also implement the delay loading of the picture.

Here is the implementation code, which I wrote as a jquery plugin.

Copy Code code as follows:

(function ($) {
$.fn.imglazyload = function (options) {
var o = $.extend ({
attr: ' Lazy-src ',
Container:window,
Event: ' Scroll ',
Fadein:false,
threshold:0,
Vertical:true
}, Options),

  event = o.event,
  vertical = o.vertical,
  container = $ (o.container),
  threshold = o.threshold, 
  //convert jquery objects to DOM arrays for easy operation
  elems = $. Makearray ($ (this)),   
  dataname = ' imglazyload_offset ',   
   OFFSET = vertical? ' Top ': ' Left ',
  scroll = vertical? ' ScrollTop ': ' ScrollLeft ',    
  winsize = vertical? Container.height (): Container.width (),
  scrollcoord = container[SCROLL] (),
  docsize = winsize + Scrollcoord;

 //Delayed-loaded triggers  
 var trigger = {

Init:function (coord) {
return coord >= Scrollcoord &&
Coord <= (docsize + threshold);
},

Scroll:function (coord) {
var Scrollcoord = container[SCROLL] ();
return coord >= Scrollcoord &&
Coord <= (winsize + Scrollcoord + threshold);
},

Resize:function (coord) {
var Scrollcoord = container[SCROLL] (),
Winsize = vertical?
Container.height ():
Container.width ();
return coord >= Scrollcoord &&
Coord <= (winsize + Scrollcoord + threshold);
}
};

var loader = function (Triggerelem, event) {
var i = 0,
Iscustom = False,
Istrigger, Coord, Elem, $elem, LAZYSRC;

Custom events can only be triggered, no need to judge
if (event) {
if (event!== ' scroll ' && event!== ' resize ') {
Iscustom = true;
}
}
else{
event = ' init ';
}

for (; i < elems.length; i++) {
Istrigger = false;
Elem = Elems[i];
$elem = $ (elem);
LAZYSRC = $elem. attr (o.attr);

if (!lazysrc | | elem.src = = LAZYSRC) {
Continue
}
Gets the offset value from the cache before the computed value is obtained in the cache.
The computed value is cached to avoid reflow caused by repeated fetching
coord = $elem. Data (Dataname);

if (coord = = undefined) {
coord = $elem. Offset () [offset];
$elem. Data (Dataname, coord);
}

Istrigger = Iscustom | | trigger[Event] (coord);

if (Istrigger) {
Load picture
ELEM.SRC = LAZYSRC;
if (O.fadein) {
$elem. Hide (). FadeIn ();
}
Remove Cache
$elem. Removedata (Dataname);
Remove the DOM from the DOM array
Elems.splice (i--, 1);
}
}

Uninstall triggered events after all pictures have been loaded
if (!elems.length) {
if (Triggerelem) {
Triggerelem.unbind (event, fire);
}
else{
Container.unbind (O.event, fire);
}
$ (window). Unbind (' Resize ', fire);
Elems = null;
}

};

var fire = function (e) {
Loader ($ (this), e.type);
};

Binding events
container = Event = = ' scroll '? Container: $ (this);
Container.bind (event, fire);
$ (window). Bind (' resize ', fire);

Class
Loader ();

return this;
};

}) (JQuery);


Call:

Copy Code code as follows:

$ (' img '). Imglazyload ({
Event: ' Scroll ',
attr: ' Lazy-src '
});

The default invocation can omit all parameters.
Copy Code code as follows:
$ (' img '). Imglazyload ();

Picture delay-Loaded Plug-in API description:

attr string
The name of the property that holds the real address of the picture, corresponds to the HTML, and the default is LAZY-SRC.

Container Dom & Selector
The default container is window, which allows you to customize the container.

Event Stirng
Trigger the type of event loaded by the picture, default to Window.onscroll event

FadeIn Boolean
Whether to use the Fadein effect of jquery to display, the default is False.

Threshold number
The page scrolls to load at a specified distance from the picture, and the default is 0.

Vertical Boolean
Whether to scroll horizontally, default to True (Portrait).

Loadscript (enhanced version of the feature) Boolean
Whether to load JavaScript advertisement pictures without blocking, false by default.

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.