jquery implementation of the picture on-demand delay loading principle

Source: Internet
Author: User
Tags delete cache

Why do we need to load pictures on demand?

The picture in the website can make the website add a lot of "color", but a lot of pictures will make us Open the speed down, but we have to use these graphs, we can disguise the loading of these pictures, common with some list page ah, or large data of the homepage, or "All is Graph" page, Then this picture loading is significantly important, such as Jd,taobao what is in use, so that you are not alone!

Data display by on-demand loading pictures can greatly improve the opening speed of the site!

1, first we have to change the HTML structure of these images, the picture of SRC into a "1*1" Transparent gif picture (don't say you won't do this OH), and then the real path of the picture to the picture label a placeholder attribute, such as: data-src= "picture True path"; This step can ensure that the page in the loading time each picture only loads a very small figure, in order to ensure open speed, because the real path is not in the SRC attribute, here remember, SRC can not give empty!

2, with JS to determine the location of the picture, and to the window bound scroll, resize event, if the picture is visible to replace the real placeholder value to the picture of SRC, and delete the placeholder attributes,

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 ()//Calculation picture top-scroll bar top
        > $ (window). Height ()) {//If the picture is not visible
            return ;//regardless of
       } else {
             othis.attr (' src ', othis.attr (' data-src ')). Removeattr (' data-src '); replace the placeholder value and delete the placeholder property when visible
       }
   });
}
fn ();
$window. Scroll (FN). Resize (FN);/bind event


The above code is excerpted from the eight round package, but because lets you see more thoroughly changed the source code, is not the eight round package source Ah ...

3, actually you're already OK now, but you will find some can optimize the place, for example: 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 use CSS to write a loading background gif picture;

The code is as follows Copy Code


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


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

Note: When you play these very familiar with the time you should be written as a plug-in, and the other judge picture can be seen is only a simple judgment, if the user in the load when the direct press of the keyboard end key or users open on the smallest side, then your picture all of a sudden loaded up, To solve this problem, we only need to deepen the judgment when the judgment is visible, such as:

The code is as follows Copy Code


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


whether it has an impact on SEO

No impact, but it should be noted that now Baidu has begun to capture a large number of pictures of the page, the proposal in the details of the page when the first image of the product/commodity does not use on-demand loading, because such loading may not be seo/seo.html "target=" _blank "> Search engine captured;"
A common problem of online plug-ins

See the Internet has a lot of implementation picture loading, but many did not give a clear change to the HTML code steps, just use JS operation, after viewing the source code found, are in JS to the picture of the real path to save, as shown:

Picture Delay loading

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

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; /* No loading effect when loading * *


/**
* @name Picture Lazy Load Plugin
* @description jQuery extension, can make rolling load, click Load, etc., rely on msc,jquery,msc.event, currently only on window operation
* @version 1.0
* @author Xieliang
* @demo
* 1, delayed loading
* $ ("#id img.imgload"). Imgload ()//default real picture path in data-src, default to fade in
* 2, modify the real picture path
* $ ("img.imgload"). Imgload ({attr: "DATA-IMG-SRC"});
* 3, modify fade effect
* $ ("img"). Imgload ({effect: "show"});//No Fade effect
* 4, custom events
* $ ("img"). Imgload ({event: "Xieliang"});//define Event name
* Where needed $ ("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 self = this;
if (!self.length | | self[0].nodename.tolowercase ()!== "img") {//Return to yourself if the selector is not or is not a picture www.111cn.net
return self;
};
var conf = a.extend ({}, a.fn.imgload.defaults, config | | {});//merge
var cache = {};//Store picture objects
var imglength = total number of self.length;//pictures
var imgi = number of pictures loaded 0;//
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");//Trigger Load event for current picture
};
};
if (IMGI >= imglength) {//If load is greater than or equal to total
Imglength = IMGI = cache = null;//Qing
Msc.event.resize.remove ("Imgload");//Removing Resize Event
Return false;//returns false to remove scroll event
};
});
Msc.event.resize.add ("Imgload", function () {//Set Resize trigger event
Scroll.trigger ("Imgload");
});
settimeout (function () {
Scroll.trigger ("Imgload"); The default load trigger resolves a picture that may not be at the top without loading when the scroll bar load completes
}, 50);
};
Return Self.each (function (i) {//Traverse all pictures
var $img = $ (this);
Cache[i] = $img;//Fill out the picture in the cache
$img. One ("Imgload",//binding one-time event
function () {
if (!this[' _imgload ']) {//To match the tab component to prevent repeated loading
this[' _imgload '] = 1;
$ ("function () {
$img. Hide (). attr ("src", $img. attr (conf.attr)) [Conf.effect] (). removeattr (conf.attr);//Show The picture
}). attr ("src", $img. attr (conf.attr));
}
Delete cache[i];//deletes the cache in the
imgi++;//let the loaded number increase itself
});
if ("scroll"!== conf.event) {//If not a scrolling event
$img. One (conf.event,//binding one-time event triggers
function () {
if (Cache[i]) {//if the cache presence is considered not loaded
Cache[i].trigger ("Imgload");/Trigger Load
};
});
};
});
};

    a.fn.imgload.defaults = {//default configuration
        attr: "Data-src ",//Connect placeholder
        effect:" FadeIn ",//Effect
         event: "Scroll",//Events
        threshold:0//offset, can be positive/negative
    };
} (jQuery);

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.