Pre-loading and delay loading of images in jquery

Source: Internet
Author: User
Tags object object

There are many projects often need to judge the picture after loading completed the appropriate operation, or the need to delay the loading of pictures, although the internet has a very good plug-ins, but for these effects have to load a separate plug-in words always feel a little uncomfortable, simply write a method yourself:

The code is as follows Copy Code

function Loadimg (arr,funloading,funonload,funonerror) {
var numloaded=0,
Numerror=0,
Isobject=object.prototype.tostring.call (arr) = = = "[Object Object]"? True:false;

var arr=isobject? Arr.get (): arr;
For (A in arr) {
var src=isobject? $ (Arr[a]). attr ("Data-src"): Arr[a];
Preload (Src,arr[a]);
}

function preload (src,obj) {
var img=new Image ();
Img.onload=function () {
numloaded++;
Funloading && funloading (numloaded,arr.length,src,obj);
Funonload && numloaded==arr.length && funonload (numerror);
};
Img.onerror=function () {
numloaded++;
numerror++;
Funonerror && Funonerror (numloaded,arr.length,src,obj);
}
IMG.SRC=SRC;
}

}

Parameter description:

Arr: It can be an array of image paths, or it can be a selected IMG jquery object;
Funloading: Each individual picture loaded after the completion of the operation performed;
Funonload: All pictures are loaded after the completion of the operation;
Funonerror: An action that occurs when a single picture is loaded.

Such as:

The code is as follows Copy Code
var imgonload=function (Errors) {
/*errors: Load error number of pictures;
Console.log ("Loaded," +errors+ "Images loaded error!");
}

var funloading=function (n,total,src,obj) {
/*
N: number of completed loads;
Total: Number of pictures to load;
SRC: Currently loading the completed picture path;
Obj: When the arr passed in the LOADIMG function is the array that holds the path of the picture, OBJ=SRC is the picture path,
When Arr is a jquery object, obj is the currently loaded, completed IMG DOM object.
*/
Console.log (n+ "of" +total+ "pic loaded.", SRC);
var newimg = document.createelement ("img");
NEWIMG.SRC=SRC;
$ ("Body"). Append (newimg). FadeIn ();
}

var funloading_obj=function (n,total,src,obj) {
Console.log (n+ "of" +total+ "pic loaded.", SRC);
$ (obj). attr ("src", SRC);
$ (obj). fadeIn (200);
}

var funonerror=function (n,total,src,obj) {
Console.log ("The" +n+ "St img Loaded error!");
}

Call Example:

The code is as follows Copy Code

Console.log ("Loading ...");
Loadimg ($ ("img"), funloading_obj,imgonload,funonerror);
/*loadimg (["Yun_qi_img/block.gif",
"/20120531/1670912_103610084349_2.jpg",
"/20120616/4952071_130629530136_2.jpg",
"/20120610/1723580_105037029000_2.jpg",
"Yun_qi_img/block.gif"
],FUNLOADING,IMGONLOAD,FUNONERROR);


The above is the original ecological writing, the following we introduce a lazy load, delayed loading of the image of the JQuery plugin

Lazy Load relies on jQuery. Please add the following code to the page Head area:

The code is as follows Copy Code
<script src= "Jquery.js" type= "Text/javascript" ></script>
<script src= "Jquery.lazyload.js" type= "Text/javascript" ></script>

You must modify the HTML code. Set up a booth picture in the SRC attribute, and the demo page uses the 1x1 pixel gray GIF picture. And you need to set the URL of the real picture to the Data-original property. Here you can define a specific class to get a picture object that needs to be loaded late. In this way you can simply control the plug-in bindings.

The code is as follows Copy Code

The code to process the picture is as follows.

The code is as follows Copy Code
$ ("Img.lazy"). Lazyload ();

This will allow all pictures with class lazy to be delayed loading. You can refer to the basic options demo

Setting sensitivity
Almost all JavaScript in the browser is active. However, you may still want to display real images on clients that do not support JavaScript. When the browser does not support JavaScript gracefully demote, you can put the real picture fragment in the Write <noscript> tag.

The code is as follows Copy Code
<noscript></noscript>"

You can hide placeholders through CSS.

The code is as follows Copy Code
. Lazy {
Display:none;
}

In browsers that support JavaScript, you must display placeholders when DOM ready, which can be done while the plug-in is initialized.

The code is as follows Copy Code
$ ("Img.lazy"). Show (). Lazyload ();

These are optional, but they should be done if you want the plug-ins to degrade gracefully.

Setting sensitivity
By default, pictures are loaded when they appear on the screen. If you want to load the picture in advance, you can set the threshold option and set the threshold to 200 so that the picture is loaded ahead of 200 pixels from the screen.

The code is as follows Copy Code
$ ("Img.lazy"). Lazyload ({threshold:200});

Placeholder picture
You can also set up a placeholder picture and define events to trigger the load action. Then you need to set a URL address for the placeholder picture. Transparent, gray and white images of 1x1 pixels are already included in the plugin.

Event Trigger loading
Events can be any jQuery time, such as Click and MouseOver. You can also use custom events, such as: Sporty and foobar. Waits by default until the user scrolls to the location of the picture on the window. To prevent loading pictures before the gray placeholder picture is clicked, you can do this:

The code is as follows Copy Code
$ ("img"). Lazyload ({
PLACEHOLDER: "Img/grey.gif",
Event: "Click"
});

Use special effects
When the picture is fully loaded, the plugin uses the show () method to display the graph by default. In fact, you can use any special effects you want to deal with. The following code uses the FadeIn effect. This is the effect demo page.

The code is as follows Copy Code
$ ("Img.lazy"). Lazyload ({
Effect: "FadeIn"
});

The picture is inside the container
You can use the plugin on a picture of a scrollable container, such as a DIV element with a scroll bar. All you have to do is define the container as a JQuery object and upload it as a parameter to the initialization method. This is the Horizontal scrolling demo page and the Vertical scrolling presentation page.

The code is as follows Copy Code
#container {
height:600px;
Overflow:scroll;
}
$ ("Img.lazy"). Lazyload ({
Container: $ ("#container")
});

When pictures are not arranged in order
When scrolling the page, Lazy load loops to the loaded picture. Detects whether a picture is in the viewable area in a loop. By default, the loop stops when you find the first picture that is not in the visible area. Pictures are considered streaming, and the order of the pictures in the page is the same as in the HTML code. But in some layouts, such assumptions are not tenable. However, you can control the load behavior with the FAILURELIMIT option.

The code is as follows Copy Code
$ ("Img.lazy"). Lazyload ({
Failure_limit:10
});

The Failurelimit is set to 10 so the plugin finds 10 pictures that are not in the visible area before stopping the search. If you have a wretched layout, please set this parameter a little higher.

Lazy Load Picture
An incomplete feature of the Lazy load plug-in, but this can also be used to implement a delayed loading of the picture. The following code implements the page load completion and then loads it. After the page has finished loading for 5 seconds, the picture in the specified range is automatically loaded. This is the Lazy Load demo page.

The code is as follows Copy Code
$ (function () {
$ ("Img:below-the-fold"). Lazyload ({
Event: "Sporty"
});
});
$ (window). Bind ("Load", function () {
var timeout = settimeout (function () {$ ("Img.lazy"). Trigger ("sporty")}, 5000);
});

Load a hidden picture
There may be a lot of hidden pictures buried on your page. For example, Plug-ins used to filter the list, you can constantly modify the list of the purpose of the display status. To improve performance, Lazy Load ignores hidden pictures by default. If you want to load a hidden picture, set Skip_invisible to False

  code is as follows copy code

$ ("Img.lazy "). Lazyload ({
    skip_invisible:false
});

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.