jquery implementation picture on-demand lazy loading principle

Source: Internet
Author: User
Tags delete cache

Why do we need images to load on demand?

The pictures in the website can make the website add a lot of "color", but a lot of pictures will make us turn the speed down, but we have to use these pictures, we can load these images in disguise, common with some list page ah, or Big Data homepage ah, or "All is map" of the page, Then this image loading is very important, such as Jd,taobao what is in use, so that you are not alone!

Data display can greatly improve the speed of website opening by loading images on demand!

1, first we have to change the HTML structure of these images, the image of the SRC replaced by a "1*1" Transparent gif picture (do not say you do not do this OH), and then the picture's true path to a placeholder attribute in the picture tag, such as: data-src= "picture True path"; This step can ensure that the page at the time of loading each picture only a small map to ensure that the opening speed, because the real path is not on the SRC attribute, here remember, SRC can not be empty!

2, with JS to determine the location of the picture, and to the window binding scroll, resize event, if the picture is visible then replace the real placeholder value to the image src, and delete the placeholder properties,

The code is as follows Copy Code

var fn = function () {
$ ("#id img"). each (function () {//Traverse all pictures
var othis = $ (this),//Current Picture Object
top = Othis.offset (). Top-$ (window). scrolltop ();//Calculate picture top-scroll bar top
if (Top > $ (Window). Height ()) {//If the picture is not visible
return;//no matter
} else {
Othis.attr (' src ', othis.attr (' data-src ')). Removeattr (' data-src ');//The placeholder value is replaced and the placeholder property is deleted when visible
}
});
}
FN ();
$window. Scroll (FN). Resize (FN);//Bind Event


The above code from the eight round package, but because let you see more thoroughly changed the source, not the source of eight round package ah ...

3, in fact, you are now OK, but you will find some optimization, such as: JS code optimization Ah, because a lot of execution scroll event is very not handsome one thing, you have to cache + delay, there are pictures in the loading time to a loading, no problem, This can give this img to write a loading background gif with CSS;

The code is as follows Copy Code


Img.load{background:url ('/images/loading.gif ') No-repeat Center Center;} /* Not loading effect when loading */


4, the $ ("#id img") is a picture selector, you can add a class to the picture, and then use $ ("img.loadimg") and so on, so it is more convenient only to the need to delay loading the image added;

Note: When you put these play very familiar when you should be written into the plug-in, and this judgment picture is only a simple judgment, if the user directly after loading the keyboard end key or user open on the minimum surface, then your picture all of a sudden loaded up, To solve this problem, you only need to deepen the judgment when the judgment is visible, code such as:

The code is as follows Copy Code


The If (window). scrolltop () + $ (window). Height () >= ($ (this). Offset (). Top) && ($ (this). Offset (). Top + $ (this). Height () >= $ (window). scrolltop ()) {//Advanced visible
}


Whether it has an impact on SEO

There is no impact, but note that now Baidu has begun to grab a lot of pictures of the page, it is recommended that the details of the product/product in the first picture does not use on-demand loading, because such loading may not be seo/seo.html "target=" _blank "> search engine capture;
A common problem of online plugins

See online there are many implementation of picture loading, but many did not give explicit steps to change the HTML code, just use JS operation, after viewing the source code found, are in JS in the picture of the true path to save up,:

Picture Lazy Loading

But after the console network view, this will be in your JS before the execution of all the pictures have been requested, that is, did not achieve the optimized effect!

Let's take a look at the following example

The code is as follows Copy Code


Css
Img.load{background:url ('/iamges/loading.gif ') No-repeat Center Center;} /* Not loading effect when loading */


/**
* @name Picture Lazy Loading Plugin
* @description jQuery extension, can make rolling load, click Load, etc., rely on msc,jquery,msc.event, currently only operate on window
* @version 1.0
* @author Xieliang
* @demo
* 1, delayed loading
* $ ("#id img.imgload"). Imgload ();//default true picture path in Data-src, default is fade in
* 2, modify the real picture path
* $ ("img.imgload"). Imgload ({attr: "DATA-IMG-SRC"});
* 3, modify fade-in effect
* $ ("img"). Imgload ({effect: "show"});//No fade-in effect
* 4, custom events
* $ ("img"). Imgload ({event: "Xieliang"});//define Event name
* In place of Need $ ("img"). Trigger ("Xieliang");//Trigger Load
* 5, set screen offset, support positive, negative
* $ ("img"). Imgload ({threshold:-100});
*/
;(function (a) {
"Use strict";
A.fn.imgload = function (config) {
var = this;
if (!self.length | | self[0].nodename.tolowercase ()!== "img") {//If the selector does not have or is not a picture then return to itself www.111cn.net
return self;
};
var conf = a.extend ({}, a.fn.imgload.defaults, config | | {});//merge
var cache = {};//Store Picture object
var imglength = self.length;//Total number of pictures
var IMGI = 0;//number of pictures loaded
if ("scroll" = = = = Conf.event) {//If it is a scrolling event
var scroll = new Msc.event ("scroll", 0);//Create 0 deferred scrolling
Scroll.add ("Imgload", function (obj) {
For (var item in cache) {//Run Picture object cache
if (Obj.scrolltop + obj.height >= (Cache[item].offset (). Top + Conf.threshold)) {//If the picture is visible
if (Obj.scrolltop + obj.height >= (Cache[item].offset (). Top + conf.threshold) && (Cache[item].offset (). top+ Cache[item].height () >= obj.scrolltop)) {//Advanced visible
Cache[item].trigger ("Imgload");//Load event that triggers the current picture
};
};
if (IMGI >= imglength) {//If load is greater than or equal to total
Imglength = IMGI = cache = null;//Clear
Msc.event.resize.remove ("Imgload");//Remove Resize Event
Return false;//returns false Remove Scroll event
};
});
Msc.event.resize.add ("Imgload", function () {//Setting resize when the event is triggered
Scroll.trigger ("Imgload");
});
SetTimeout (function () {
Scroll.trigger ("Imgload"); The default load trigger, resolves that the scroll bar may not load at the top without loading the picture
}, 50);
};
Return Self.each (function (i) {//Traverse all pictures
var $img = $ (this);
Cache[i] = $img;//fill in the picture in the cache
$img. One ("Imgload",//Bind one-time event
function () {
if (!this[' _imgload ')} {//In order to fit the tab component to prevent repeated loading
this[' _imgload '] = 1;
$ ("function () {
$img. Hide (). attr ("src", $img. attr (conf.attr)) [Conf.effect] (). removeattr (conf.attr);//Display the picture
}). attr ("src", $img. attr (conf.attr));
}
Delete cache[i];//in the cache.
imgi++;//let the loaded number self-increment
});
if ("scroll"!== conf.event) {//If not a scrolling event
$img. One (conf.event,//binding one-time event trigger
function () {
if (Cache[i]) {//If the cache exists it is considered not loaded
Cache[i].trigger ("Imgload");//Trigger Load
};
});
};
});
};

A.fn.imgload.defaults = {//default configuration
attr: "Data-src",//Connection placeholder
Effect: "FadeIn",//Effect
Event: "Scroll",//Events
threshold:0//offset, can be positive/negative
};
} (JQuery));

jquery implementation picture on-demand lazy loading principle

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.