Jquery implements the method of image preloading and delayed loading

  • 2020-05-09 18:06:20
  • OfStack

The example of this article describes the method of Jquery to realize image preloading and delayed loading. Share with you for your reference. The specific analysis is as follows:

A lot of projects often need to judge the image loading after the completion of the corresponding operation, or need to delay the loading of the image, although there are already good online plug-ins, but it is always a little uncomfortable to have to load a separate plug-in for these effects, I simply wrote a method:

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 selected from img.
funLoading: the operation performed after each individual picture is loaded;
funOnLoad: the operation after all the pictures are loaded;
funOnError: operation when a single image is loaded incorrectly.

Such as:

var imgonload=function(errors){
        /*errors : the number of images loaded incorrectly; */
 console.log("loaded,"+errors+" images loaded error!");
}
 
var funloading=function(n,total,src,obj){
        /*
        n : the number of completed loads;
        total : the total number of images to be loaded;
        src : the image path that has been loaded;
        obj : when loadimg Passed in from the function arr When storing an array of image paths, obj=src , is the image path,
               when arr for jquery Object, obj Is the current load 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:
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 written in the original style. Next, we introduce an jQuery plugin based on Lazy Load, which lazily loads images

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

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>

You must modify the HTML code. Set the booth image in the src property, and the demo page USES the 1x1 pixel gray GIF image. You also need to set the URL of the real image to the data-original property.
<img class="lazy" src="img/grey.gif" data-original="img/example.jpg"  width="640" heigh="480">

The code for processing the image is as follows.
$("img.lazy").lazyload();

This causes all images with class as lazy to be lazy-loaded. See the base option demo

Set sensitivity

Almost all browsers have JavaScript enabled. However, you may still want to be able to display real images on clients that don't support JavaScript < noscript > Tags.

<img class="lazy" src="img/grey.gif" data-original="img/example.jpg"  width="640" heigh="480">
<noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>

Placeholders can be hidden by CSS.
.lazy {
  display: none;
}

In browsers that support JavaScript, you must display placeholders at DOM ready, which can be done at the same time as the plug-in initializes.
$("img.lazy").show().lazyload();

These are optional, but should be done if you want the plugin to degrade smoothly.

Set sensitivity

By default the image will be loaded when it appears on the screen. If you want to load the image ahead of time, you can set the option threshold and set threshold to 200 to load the image ahead of time when it is 200 pixels away from the screen.

$("img.lazy").lazyload({ threshold : 200 });

Placeholder images

You can also set a placeholder image and define an event to trigger the loading action. You need to set an URL address for the placeholder image. Transparent, grey and white 1x1 pixel images are already included in the plugin.

Event-triggered loading

The event can be any jQuery time, such as click and mouseover. You can also use custom events, such as sporty and foobar. By default, it is in a wait state until the user scrolls to where the image is in the window.

$("img").lazyload({
 placeholder : "img/grey.gif",
 event : "click"
});

Use the special effects

When the image is fully loaded, the plugin USES the show() method by default to display the image. You can use any effect you want. The code below USES the FadeIn effect. This is the effects demo page.

$("img.lazy").lazyload({ 
    effect : "fadeIn"
});

The picture is inside the container

You can use the plugin on scrollable container images, such as the DIV element with a scrollbar. All you have to do is define the container as an jQuery object and pass it as a parameter to the initialization method.

#container {
    height: 600px;
    overflow: scroll;
}
$("img.lazy").lazyload({        
     container: $("#container")
});

When the pictures are not arranged in order

Will scroll, Lazy Load cycle to load images. In a loop detection image is in the visible area. The default is found 1 stop cycle when zhang is not in the visible region of the image. Image is considered to be the distribution of the flow, the picture in the page order in the same order and HTML code. But in 1 some layout, this assumption is not set up. But you can load through failurelimit options to control behavior.

$("img.lazy").lazyload({ 
    failure_limit : 10
});

Setting failurelimit to 10 stops the search until the plugin finds 10 images that are not visible. If you have a creepy layout, set this to 1 point higher.

Lazy loading picture

An incomplete feature of the Lazy Load plugin, but it can also be used for lazy loading of images. The following code implements loading after the page is loaded. Images in the specified area are automatically loaded after the page is loaded for 5 seconds. This is the lazy loading demo page.

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

Load the hidden image

If you want to load a hidden image, skip_invisible is false. If you want to load a hidden image, skip_invisible is false

$("img.lazy").lazyload({ 
    skip_invisible : false
});

I hope this article has been helpful to your javascript programming.


Related articles: