Jquery image delayed loading front-end development skills required series _ jquery

Source: Internet
Author: User
On the Internet, you will often see some very long web pages that will delay loading images. I think this is a pay-as-you-go approach. The web pages only load the images after those who want to continue browsing the Web pages, while minimizing server load and traffic without affecting user experience, most shopping websites use this loading method. Today, I found a plug-in for delayed image loading on a website of a netizen. It is very useful. Here I will introduce it.
First, we will introduce the principle of delayed loading. We need to save the real address of the image in a custom attribute first (you can use the attribute name for your use. Here we use lazy-src ), the src attribute of the image is replaced by a placeholder image. The smaller the placeholder image, the better. It basically only works and does not show up.

The Code is as follows:






First. When the page starts to load, the browser will get the position of all the images on the current page and cache them (when the offset value is obtained, the reflow of the page will be triggered) to calculate the visible area, when the position of the image appears in the visible area, use js to dynamically Replace the src value in the image label with the actual address of the image. Then, the image that appears in the visible area starts to be loaded.
Second. When you scroll down the page, use js to re-calculate whether an image appears in the visible area for the first time. If yes, you have just replaced the src value of the image and started loading the real image. To avoid Memory leakage caused by repeated operations, You Need To uninstall the trigger event after loading all the images.
Last. This article regards the entire window as a large container. If you want to, you can also set a small container on the page to implement delayed image loading in the small container. The principle is simple, but its applications are diverse.
You can see the demonstration of delayed image loading from the following address, but try to use the corresponding tools (firebug, Fiddler2) to monitor the effect of delayed image loading.
The code for the image delay plugin is as follows:

The Code is as follows:


Code of the image delay loading plug-in
(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 );


The plug-in API is described as follows:
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.

Note: Please indicate the source for reprinting. Author: Ailian Emy
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.