Home > Web Front-end > JS Tutorial > body text

jquery image lazy loading essential front-end development skills series_jquery

WBOY
Release: 2016-05-16 17:52:42
Original
1123 people have browsed it

Currently, major shopping websites all adopt this loading method. Today, I found a plugin for delayed loading of images on a netizen’s website. It’s very useful. I’ll introduce it here.
First, let’s introduce the principle of image lazy loading. We need to first save the real address of the image in a custom attribute (the attribute name is up to you, here I use lazy-src), and replace the src attribute of the image with a placeholder image. This occupancy Of course, the smaller the picture, the better. It basically just works and doesn't show up.

Copy code The code is as follows:





First. When the page starts loading, the browser will obtain the positions of all images in the current page and cache them (when the offset value is obtained, the reflow of the page will be triggered), calculate the visible area, and when the position of the image appears in the visible area, Use js to dynamically replace the src value in the image tag with the real address of the image. At this time, the image that just appeared in the visible area starts to load.
Secondly. When the user scrolls down the page, js is used to calculate again whether there are pictures that appear in the visible area for the first time. If so, the src values ​​of these pictures are just replaced and the real pictures are loaded. In order to avoid memory leaks caused by repeated operations, the corresponding trigger events need to be unloaded after all images are loaded.
Finally. This article treats the entire window as a large container. If you like, you can also set up a small container in the page. In the small container, you can also implement delayed loading of images. Although the principle is simple, the applications are diverse.
You can see a demonstration of delayed image loading from the address below, but try to use the corresponding tools (firebug, Fiddler2) to monitor the effect of delayed image loading.
The code for the image lazy loading plug-in is as follows:
Copy the code The code is as follows:

Image lazy loading plug-in code
(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 object into DOM Arrays are easy to operate
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;
/ / Lazy loading trigger
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 only need to 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;
}
// First get the offset value from the cache, Get the calculated value only if it is not in the cache,
// Cache the calculated value to avoid reflow caused by repeated acquisition
coord = $elem.data( dataName );
if( coord === undefined ){
coord = $elem.offset()[ OFFSET ];
$elem.data( dataName, coord );
}
isTrigger = isCustom || trigger[ event ]( coord );
if( isTrigger ){
// Load image
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 );
}
}
//Unload the trigger event after all images are 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 );
};
// Bind event
container = event === 'scroll' ? container : $( this );
container.bind( event, fire );
$( window ).bind( 'resize', fire );
/ / Initialize
loader();
return this;
};
})( jQuery );

The plug-in API description for this is as follows:
attr string
The attribute name that stores the real address of the image, corresponding to HTML, and the default is lazy-src.
container dom & selector
The default container is window, and the container can be customized.
event stirng
The event type that triggers image loading, the default is window.onscroll event
fadeIn boolean
Whether to use jQuery's fadeIn effect to display, the default is false.
threshold number
The page will be loaded when it is scrolled to the specified distance from the image. The default is 0.
vertical boolean
Whether to scroll horizontally, the default is true (vertical).
loadScript (enhanced version of the function) boolean
Whether to load JavaScript advertising images without blocking, the default is false.

Note: Please indicate the source when reprinting. Author: Ailian Academy
Related labels:
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