Home  >  Article  >  Web Front-end  >  How to implement image preloading and delayed loading with Jquery_jquery

How to implement image preloading and delayed loading with Jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:25:19976browse

The example in this article describes how Jquery implements image preloading and delayed loading. Share it with everyone for your reference. The specific analysis is as follows:

There are many projects that often need to determine whether to perform corresponding operations after the image is loaded, or to delay loading of the image. Although there are already very good plug-ins on the Internet, it always feels a bit awkward to have to load a separate plug-in for these effects. It’s so comfortable, I just wrote a method myself:

Copy code The code is as follows:
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 to store the image path, or it can be the jquery object of the selected img;
funLoading: The operation performed after each individual image is loaded;
funOnLoad: Operation after all images are loaded;
funOnError: Operation when a single image loading error occurs.

For example:

Copy code The code is as follows:
var imgonload=function(errors){
             /*errors: Number of pictures with loading errors;*/
console.log("loaded," errors " images loaded error!");
}

var funloading=function(n,total,src,obj){
          /*
n: The number of loaded items;
            total: the total number of images to be loaded;
SRC: The picture path that is currently loaded;
​​​​ obj: When the arr passed in the loadimg function is an array storing the image path, obj=src is the image path,
When arr is a jquery object, obj is the currently loaded 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:
Copy code The code is as follows:
console.log("loading...");
loadimg($("img"),funloading_obj,imgonload,funOnError);
/*loadimg(["http://pic22.nipic.com/20120619/9607634_212642465144_2.jpg",
"/20120531/1670912_103610084349_2.jpg",
"/20120616/4952071_130629530136_2.jpg",
"/20120610/1723580_105037029000_2.jpg",
"http://pic22.nipic.com/20120617/2572038_125013326121_2.jpg"
],funloading,imgonload,funOnError);*/

The above is the original writing method. Next we introduce a jQuery plug-in for lazy loading of images based on Lazy Load

Lazy Load depends on jQuery. Please add the following code to the head area of ​​the page:

Copy code The code is as follows:

You must modify the HTML code. Set the booth symbol image in the src attribute. The demo page uses a 1x1 pixel gray GIF image. And you need to set the URL of the real image to the data-original attribute. Here you can define a specific class to obtain the lazy loading Image object. This way you can simply control plugin bindings.
Copy code The code is as follows:

The code for processing images is as follows.
Copy code The code is as follows:
$("img.lazy").lazyload();

This will cause all images with class lazy to be loaded lazily. You can refer to the basic options demo

Set sensitivity

JavaScript is enabled in almost all browsers. However, you may still want to display real images on clients that do not support JavaScript. To degrade gracefully when the browser does not support JavaScript, you can write real image fragments

Copy code The code is as follows:


Placeholders can be hidden via CSS.
Copy code The code is as follows:
.lazy {
display: none;
}

In browsers that support JavaScript, you must display the placeholder when the DOM is ready, which can be done at the same time as the plugin is initialized.
Copy code The code is as follows:
$("img.lazy").show().lazyload();

These are optional, but should be done if you want your plugin to downgrade gracefully.

Set sensitivity

By default, the image will be loaded when it appears on the screen. If you want to load the image in advance, you can set the threshold option. Set threshold to 200 to make the image load in advance when it is 200 pixels away from the screen.

Copy code The code is as follows:
$("img.lazy").lazyload({ threshold : 200 });

Placeholder image

You can also set a placeholder image and define events to trigger the loading action. At this time, you need to set a URL address for the placeholder image. Transparent, gray and white 1x1 pixel images are already included in the plug-in.

Event triggered loading

The event can be any jQuery event, such as: click and mouseover. You can also use custom events, such as: sporty and foobar. By default, it is in a waiting state until the user scrolls to the position of the picture on the window. In gray To prevent the placeholder image from loading until it is clicked, you can do this:

Copy code The code is as follows:
$("img").lazyload({
placeholder: "img/grey.gif",
event : "click"
});

Use special effects

When the image is fully loaded, the plug-in uses the show() method by default to display the image. In fact, you can use any special effects you want to process. The following code uses the FadeIn effect. This is the effect demonstration page.

Copy code The code is as follows:
$("img.lazy").lazyload({
Effect: "fadeIn"
});

The image is inside the container

You can use the plug-in on images in scrollable containers, such as DIV elements with scroll bars. All you have to do is define the container as a jQuery object and pass it as a parameter to the initialization method. This is a horizontal scrolling demo page and vertical scrolling demo page.

Copy code The code is as follows:
#container {
Height: 600px;
Overflow: scroll;
}
$("img.lazy").lazyload({    
container: $("#container")
});

When the pictures are not arranged in order

When scrolling the page, Lazy Load will loop through the loaded images. In the loop, it will detect whether the image is within the visible area. By default, the loop will stop when the first image that is not in the visible area is found. The image is considered Fluidly distributed, the order of the images in the page is the same as the order in the HTML code. But in some layouts, this assumption is not true. However, you can control the loading behavior through the failurelimit option.

Copy code The code is as follows:
$("img.lazy").lazyload({
Failure_limit : 10
});

Set the failurelimit to 10 so that the plugin stops searching after finding 10 images that are not in the visible area. If you have a cumbersome layout, please set this parameter higher.

Lazy loading of images

An incomplete function of the Lazy Load plug-in, but it can also be used to implement lazy loading of images. The following code implements loading after the page is loaded. 5 seconds after the page is loaded, the images in the specified area will Load automatically. This is the lazy loading demo page.

Copy code The code is as follows:
$(function() {      
$("img:below-the-fold").lazyload({
        event: "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {$("img.lazy").trigger("sporty")}, 5000);
});

Loading hidden images

There may be many hidden pictures buried on your page. For example, if the plug-in is used to filter the list, you can continuously modify the display status of each item in the list. In order to improve performance, Lazy Load ignores hidden pictures by default. If you want to load hidden images, please set skip_invisible to false

Copy code The code is as follows:
$("img.lazy").lazyload({
Skip_invisible : false
});

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn