An image delay loading plug-in implemented by jquery (including the image delay loading principle)

Source: Internet
Author: User

Delayed image loading is also called lazy loading. It is usually applied to webpages with many images. If a page has many images and the page height or width has several screens, when the page is loaded for the first time, only images in the visible area are displayed. When the page is scrolling, the image enters the visible area and then loads it. This can significantly increase the page loading speed, A smaller number of concurrent image requests can also reduce the pressure on the server. If the user just stays on the first screen, it can save traffic. If there are many images in the TAB, it can also be applied to the TAB. When the TAB is triggered, the image is loaded.

The principle of delayed image loading is relatively simple. First, the real address of the image is cached in a custom property (lazy-src, the src address is replaced by a 1x1 fully transparent placeholder image. Of course, the placeholder image can also be another image.

Copy codeThe Code is as follows:

Because javascript is used to load images, If you disable javascript, you can set an alternative solution.

Copy codeThe Code is as follows:
<Noscript> </noscript>

When the page is loaded for the first time, the position of the image in the page is obtained and cached (the value of offset will trigger the reflow of the page). The visible area is calculated. When the image position appears in the visible area, replace the src value with the actual address, and the image is loaded.

When the page is scrolling, judge whether the cached position value of the image appears in the visible area and replace src for loading. After all the images are loaded, detach the corresponding trigger event to avoid Memory leakage caused by repeated operations. When you think of the entire window as a large container, you can also set a small container on the page to implement delayed image loading in the small container.

The following is the implementation code. I have written the jQuery plug-in.

Copy codeThe Code is 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 the jQuery object to a DOM array for easy operation
Elems = $. makeArray ($ (this )),
DataName = 'imglazyload _ offset ',
OFFSET = vertical? 'Top': 'left ',
SCROLL = vertical? 'Rolltop': 'rollleft ',
WinSize = vertical? Container. height (): container. width (),
ScrollCoord = container [SCROLL] (),
DocSize = winSize + scrollCoord;

// Trigger for delayed Loading
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 be triggered without further judgment
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;
}
// Get the offset value from the cache first. The calculated value is not obtained in the cache,
// Cache the calculated value to avoid repeated reflow results
Coord = $ elem. data (dataName );

If (coord = undefined ){
Coord = $ elem. offset () [OFFSET];
$ Elem. data (dataName, coord );
}

IsTrigger = isCustom | trigger [event] (coord );

If (isTrigger ){
// Load the 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 );
}
}

// Trigger event of unmounting 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 events
Container = event === 'scroll '? Container: $ (this );
Container. bind (event, fire );
$ (Window). bind ('resize', fire );

// Initialization
Loader ();

Return this;
};

}) (JQuery );


Call:
Copy codeThe Code is as follows:
$ ('Img '). imglazyload ({
Event: 'scroll ',
Attr: 'Lazy-src'
});

All parameters can be omitted by default.
Copy codeThe Code is as follows: $ ('img '). imglazyload ();

Descriptions of the extensions for delayed image loading:

Attr string
The attribute name that stores the real image address. It corresponds to HTML. The default value is lazy-src.

Container dom & selector
The default container is window, which can be customized.

Event stirng
Event Type that triggers image loading. The default value is window. onscroll.

FadeIn boolean
Whether to use the fadeIn Effect of jQuery. The default value is false.

Threshold number
When the page is scrolled to a specified distance from the image, it is loaded. The default value is 0.

Vertical boolean
Whether to scroll horizontally. The default value is true (portrait ).

LoadScript (enhanced version) boolean
Whether to load javascript ad images without blocking. The default value is false.

Related Article

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.