Kiểm tra hình ảnh đã được tải với thư viện imagesLoaded (ok)

https://imagesloaded.desandro.com/

jQuery

You can use imagesLoaded as a jQuery Plugin.

$('#container').imagesLoaded( function() {
  // images have loaded
});
// options
$('#container').imagesLoaded( {
  // options...
  },
  function() {
    // images have loaded
  }
);

.imagesLoaded() returns a jQuery Deferred objectarrow-up-right. This allows you to use .always(), .done(), .fail() and .progress().

$('#container').imagesLoaded()
  .always( function( instance ) {
    console.log('all images loaded');
  })
  .done( function( instance ) {
    console.log('all images successfully loaded');
  })
  .fail( function() {
    console.log('all images loaded, at least one is broken');
  })
  .progress( function( instance, image ) {
    var result = image.isLoaded ? 'loaded' : 'broken';
    console.log( 'image is ' + result + ' for ' + image.img.src );
  });

Vanilla JavaScript

You can use imagesLoaded with vanilla JS.

  • elem Element, NodeList, Array, or Selector String

  • options Object

  • callback Function - function triggered after all images have been loaded

Using a callback function is the same as binding it to the always event (see below).

Bind events with vanilla JS with .on(), .off(), and .once() methods.

Background

Detect when background images have loaded, in addition to <img>s.

Set { background: true } to detect when the element's background image has loaded.

See jQuery demoarrow-up-right or vanilla JS demoarrow-up-right on CodePen.

Ví dụ 1:

Events

always

Triggered after all images have been either loaded or confirmed broken.

  • instance imagesLoaded - the imagesLoaded instance

done

Triggered after all images have successfully loaded without any broken images.

fail

Triggered after all images have been loaded with at least one broken image.

progress

Triggered after each image has been loaded.

  • instance imagesLoaded - the imagesLoaded instance

  • image LoadingImage - the LoadingImage instance of the loaded image

Last updated