For image processing, such as slide show, zoom, etc., all operations rely on completing all images.
Today, let’s look at how to determine when all images have been loaded. Before loading is complete, you can use the loading gif image to indicate that it is loading.
Monitor the load method of img and compare it every time an image is loaded. The key code is as follows:
var num = $img.length; $imgs.load(function() { num--; if (num > 0) { return; } console.log('load compeleted'); }
The Deferred object is a new feature introduced from jQuery version 1.5.0. For detailed introduction, please see the official documentation.
Simply put, the Deferred object is jQuery's callback function solution. It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface.
Ruan Yifeng has an article that introduces Deferred objects. It is written in more detail and is more useful for getting started.
Detailed explanation of jQuery’s deferred object
Here, we used:
Key code:
var defereds = [];$imgs.each(function() { var dfd = $.Deferred(); $(this).load(dfd.resolve); defereds.push(dfd); }); $.when.apply(null, defereds).done(function() { console.log('load compeleted'); });
Basic idea:
resolve(), when() after each image is loaded done() is executed when all Deferreds are completed.
Note: Because the parameters supported by $.when are $.when(dfd1, dfd2, dfd3, ...), we use apply here to accept array parameters.