Home > Web Front-end > HTML Tutorial > jQuery determines that all images have been loaded_html/css_WEB-ITnose

jQuery determines that all images have been loaded_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:39:13
Original
1213 people have browsed it

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.

1. Ordinary methods

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'); } 
Copy after login

2. Use the Deferred object in jQuery

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:

  • deferred.resolve(): Resolve a Deferred object and call any doneCallbacks with the given args.
  • deferred.when(): Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
  • deferred.done(): Add handlers to be called when the Deferred object is resolved.
  • 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'); }); 
    Copy after login

    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.

    source:php.cn
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template