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

{% file src="/files/5G29eLKKFVKXwX1y8Upz" %}

> **Chú ý: Người ta hay sử dụng imagesLoaded** kết hợp với **masonry vì sau khi load ảnh xong mới áp dụng masonry để nó không vỡ giao diện :(**

```
<!-- Made possible by the great work of David DeSandro @ https://masonry.desandro.com -->
<!-- Part 1: Add the scripts -->
<!-- Step 1: Let's start by loading jQuery. jQuery is not required for masonary to function but makes things easier  -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Step 2: Then load imagesloaded. imagesloaded makes sure the images are not displayed until they are fully loaded -->
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>
<!-- Step 3: we load masonry -->
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<!-- Part 2: Create the grid -->
<!-- Step 1: Start with a the main grid wrapper-->
<div class="grid">
  <!-- Step 2: Add grid items--->
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/00/37/03/0037037f1590875493f413c1fdbd52b1--cool-beards-inspiring-photography.jpg" />
  </div>
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/cd/90/d9/cd90d9de63fa2c8e5c5e7117e27b5c18--gritty-portrait-photography-studio-photography.jpg">
  </div>
  <!-- Step 3: repeat...--->
  <div class="grid-item">
    <img src="https://1.bp.blogspot.com/-9QM7ciGXRkQ/V1hsB-wNLBI/AAAAAAAAMoA/eYbSHs00PTAjrI4QAmvYAIGCUe1AuRAnwCLcB/s1600/bryan_cranston_0095.jpg">
  </div>
  <div class="grid-item">
    <img src="http://webneel.com/sites/default/files/images/project/best-portrait-photography-regina-pagles%20(10).jpg" />
  </div>
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/dd/45/96/dd4596b601062eb491ea9bb8e3a78062--two-faces-baby-faces.jpg" />
  </div>
  <div class="grid-item">
    <img src="http://www.marklobo.com.au/news/wp-content/uploads/2013/03/Melbourne_Portrait_Photographer_Mark_Lobo-Cowboy.jpg" />
  </div>
  <div class="grid-item">
    <img src="https://format-com-cld-res.cloudinary.com/image/private/s--PcYqe7Zw--/c_limit,g_center,h_65535,w_960/a_auto,fl_keep_iptc.progressive,q_95/145054-8576001-Rob-Green-by-Zuzana-Breznanikova_7725_b_w.jpg" />
  </div>
  <div class="grid-item">
    <img src="http://www.iefimerida.gr/sites/default/files/janbanning11.jpg" />
  </div>
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/66/bb/e7/66bbe7acc0d64da627afef440a29714b--portrait-photos-female-portrait.jpg" />
  </div>
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/25/34/b6/2534b6c18c659546463f13b2dc62d4ce--natural-portraits-female-portraits.jpg" />
  </div>
  <div class="grid-item">
    <img src="https://s-media-cache-ak0.pinimg.com/originals/8d/67/12/8d671230ced871df8428b571ed6ec192.jpg" />
  </div>
</div>
<!-- Part 3: the script call -->
<!-- Now that everything is loaded we create a script to trigger masonary on $grid. Note that this simply says: "if the images are fully loaded, trigger masnory on $grid. -->
<script>
$(".grid").imagesLoaded(function() {
  $(".grid").masonry({
    itemSelector: ".grid-item"
  });
});
</script>
<style type="text/css">
  body {
  background: #131418;
}
/* Step 1: start with resetting some defaults */
* {
  margin: 0 auto;
  padding: 0;
  max-width: 100%;
}
/* Step 2: center things inside the grid and clear some space around it by setting a device based max-width and margin*/
.grid {
  text-align: center;
  max-width: 95vw;
  margin: 2.5vw auto;
}
/* Step 3: how big should the gap be between grid items? remember that the total gap between two items would be double what you set here since both would have that amount set as their individual padding. Also add box-sizing:border-box to make sure the padding doesn't affect the total widh of the item */
.grid-item {
  padding: 5px;
  box-sizing: border-box;
  display:inline;
}
/* Step 4: Add media queries (subjective) to make the whole grid resposive. */
@media (min-width: 500px) {
  .grid-item {
    width: 50%;
  }
}
@media (min-width: 1000px) {
  .grid-item {
    width: 33.333%;
  }
}
@media (min-width: 1700px) {
  .grid-item {
    width: 25%;
  }
}
@media (min-width: 2100px) {
  .grid-item {
    width: 20%;
  }
}
</style>
```

### &#x20;<a href="#demo" id="demo"></a>

### Ví dụ 1: Đếm số ảnh được gọi trong 1 class  <a href="#demo" id="demo"></a>

![](/files/Diz29s8x4V9sYlaiQxRK)

```
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>background</title>
  <!-- put in separate folder so JS path is different from CSS path -->
  <style type="text/css">
  .box {
    width: 300px;
    height: 300px;
    margin: 0 20px 20px 0;
    border: 1px solid;
    display: inline-block;
  }
  .orange-tree {
    background: url('http://i.imgur.com/bwy74ok.jpg');
    background-size: cover;
  }
  .thunder-cloud {
    background: url('http://i.imgur.com/ZAVN3.png');
    background-size: contain;
  }
  .multi1 {
    background:
      url("http://i.imgur.com/ZAVN3.png"),
      url('http://i.imgur.com/6UdOxeB.png') bottom right,
      url(http://i.imgur.com/LkmcILl.jpg);
    background-size: cover;
  }
  .blue {
    background: #09F;
  }
  </style>
</head>
<body>
  <h1>background</h1>
  <div class="box orange-tree"></div>
  <div class="box thunder-cloud"></div>
  <div class="box multi1"></div>
  <div class="box blue"></div>
  <script src="imagesloaded.pkgd.js"></script>
  <script>
  var imgLoad0 = imagesLoaded('.orange-tree', { background: true }, function() {
    console.log('orange tree bg images loaded aaa1', imgLoad0.images.length);
  });
  var imgLoad1 = imagesLoaded('.thunder-cloud', { background: true }, function() {
    console.log('thunder cloud bg images loaded aaa2', imgLoad1.images.length);
  });
  var imgLoad2 = imagesLoaded('.multi1', { background: true }, function() {
    console.log('multi1 bg images loaded aaa3', imgLoad2.images.length);
  });
  var imgLoad3 = imagesLoaded('.box', { background: true }, function() {
    console.log('.box bg images loaded aaa4', imgLoad3.images.length);
  });
  imgLoad3.on('progress', function(instance, image, element) {
    console.log('progress on .box aaa5', image.img.src, element.className);
  });
  </script>
</body>
</html>
```

### Demo <a href="#demo" id="demo"></a>

Add images Reset demo

[Edit this demo](https://codepen.io/desandro/pen/bIFyl) or [vanilla JS demo](https://codepen.io/desandro/pen/hlzaw) on CodePen.

Just to keep things interesting, there’s a 10% chance of adding a broken image.

### Install <a href="#install" id="install"></a>

#### Download <a href="#download" id="download"></a>

* [imagesloaded.pkgd.min.js](https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js) minified
* [imagesloaded.pkgd.js](https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.js) un-minified

#### CDN <a href="#cdn" id="cdn"></a>

```html
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>
<!-- or -->
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.js"></script>
```

#### Package managers <a href="#package-managers" id="package-managers"></a>

Install via [npm](https://www.npmjs.com/package/imagesloaded): `npm install imagesloaded`

Install via [Bower](http://bower.io/): `bower install imagesloaded --save`

### jQuery <a href="#jquery" id="jquery"></a>

You can use imagesLoaded as a jQuery Plugin.

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

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

`.imagesLoaded()` returns a [jQuery Deferred object](http://api.jquery.com/category/deferred-object/). This allows you to use `.always()`, `.done()`, `.fail()` and `.progress()`.

```js
$('#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 <a href="#vanilla-javascript" id="vanilla-javascript"></a>

You can use imagesLoaded with vanilla JS.

```js
imagesLoaded( elem, callback )
// options
imagesLoaded( elem, options, callback )
// you can use `new` if you like
new imagesLoaded( elem, callback )
```

* `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).

```js
// element
imagesLoaded( document.querySelector('#container'), function( instance ) {
  console.log('all images are loaded');
});
// selector string
imagesLoaded( '#container', function() {...});
// multiple elements
var posts = document.querySelectorAll('.post');
imagesLoaded( posts, function() {...});
```

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

```js
var imgLoad = imagesLoaded( elem );
function onAlways( instance ) {
  console.log('all images are loaded');
}
// bind with .on()
imgLoad.on( 'always', onAlways );
// unbind with .off()
imgLoad.off( 'always', onAlways );
```

### Background <a href="#background" id="background"></a>

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

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

```js
// jQuery
$('#container').imagesLoaded( { background: true }, function() {
  console.log('#container background image loaded');
});

// vanilla JS
imagesLoaded( '#container', { background: true }, function() {
  console.log('#container background image loaded');
});
```

[See jQuery demo](http://codepen.io/desandro/pen/pjVMPB) or [vanilla JS demo](http://codepen.io/desandro/pen/avKooW) on CodePen.

Set to a selector string like `{ background: '.item' }` to detect when the background images of child elements have loaded.

```js
// jQuery
$('#container').imagesLoaded( { background: '.item' }, function() {
  console.log('all .item background images loaded');
});

// vanilla JS
imagesLoaded( '#container', { background: '.item' }, function() {
  console.log('all .item background images loaded');
});
```

[See jQuery demo](http://codepen.io/desandro/pen/avKoZL) or [vanilla JS demo](http://codepen.io/desandro/pen/vNrBGz) on CodePen.

### Events <a href="#events" id="events"></a>

#### always <a href="#always" id="always"></a>

```js
// jQuery
$('#container').imagesLoaded().always( function( instance ) {
  console.log('ALWAYS - all images have been loaded');
});

// vanilla JS
imgLoad.on( 'always', function( instance ) {
  console.log('ALWAYS - all images have been loaded');
});
```

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

* `instance` *imagesLoaded* - the imagesLoaded instance

#### done <a href="#done" id="done"></a>

```js
// jQuery
$('#container').imagesLoaded().done( function( instance ) {
  console.log('DONE  - all images have been successfully loaded');
});

// vanilla JS
imgLoad.on( 'done', function( instance ) {
  console.log('DONE  - all images have been successfully loaded');
});
```

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

#### fail <a href="#fail" id="fail"></a>

```js
$('#container').imagesLoaded().fail( function( instance ) {
  console.log('FAIL - all images loaded, at least one is broken');
});

// vanilla JS
imgLoad.on( 'fail', function( instance ) {
  console.log('FAIL - all images loaded, at least one is broken');
});
```

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

#### progress <a href="#progress" id="progress"></a>

```js
imgLoad.on( 'progress', function( instance, image ) {
  var result = image.isLoaded ? 'loaded' : 'broken';
  console.log( 'image is ' + result + ' for ' + image.img.src );
});
```

Triggered after each image has been loaded.

* `instance` *imagesLoaded* - the imagesLoaded instance
* `image` *LoadingImage* - the LoadingImage instance of the loaded image

### Sponsored by Metafizzy <a href="#sponsored-by-metafizzy" id="sponsored-by-metafizzy"></a>

Development on imagesLoaded is sponsored by [Metafizzy](https://metafizzy.co/). Metafizzy makes delightful UI libraries that use imagesLoaded:

[![Isotope](https://i.imgur.com/xfGupRf.png)](https://isotope.metafizzy.co/)[![Flickity](https://i.imgur.com/8BFo4Aj.png)](https://flickity.metafizzy.co/)[![Packery](https://i.imgur.com/uRXPQfm.png)](https://packery.metafizzy.co/)

### Properties <a href="#properties" id="properties"></a>

#### LoadingImage.img <a href="#loadingimage-img" id="loadingimage-img"></a>

*Image* - The `img` element

#### LoadingImage.isLoaded <a href="#loadingimage-isloaded" id="loadingimage-isloaded"></a>

*Boolean* - `true` when the image has successfully loaded

#### imagesLoaded.images <a href="#imagesloaded-images" id="imagesloaded-images"></a>

Array of *LoadingImage* instances for each image detected

```js
var imgLoad = imagesLoaded('#container');
imgLoad.on( 'always', function() {
  console.log( imgLoad.images.length + ' images loaded' );
  // detect which image is broken
  for ( var i = 0, len = imgLoad.images.length; i < len; i++ ) {
    var image = imgLoad.images[i];
    var result = image.isLoaded ? 'loaded' : 'broken';
    console.log( 'image is ' + result + ' for ' + image.img.src );
  }
});
```

### Browserify <a href="#browserify" id="browserify"></a>

imagesLoaded works with [Browserify](http://browserify.org/).

```bash
npm install imagesloaded --save
```

```js
var imagesLoaded = require('imagesloaded');

imagesLoaded( elem, function() {...} );
```

Use `.makeJQueryPlugin` to make to use `.imagesLoaded()` jQuery plugin.

```js
var $ = require('jquery');
var imagesLoaded = require('imagesloaded');

// provide jQuery argument
imagesLoaded.makeJQueryPlugin( $ );
// now use .imagesLoaded() jQuery plugin
$('#container').imagesLoaded( function() {...});
```

### Webpack <a href="#webpack" id="webpack"></a>

Install imagesLoaded with npm.

```bash
npm install imagesloaded
```

You can then `require('imagesloaded')`.

```js
// main.js
var imagesLoaded = require('imagesloaded');

imagesLoaded( '#container', function() {
  // images have loaded
});
```

Use `.makeJQueryPlugin` to make `.imagesLoaded()` jQuery plugin.

```js
// main.js
var imagesLoaded = require('imagesloaded');
var $ = require('jquery');

// provide jQuery argument
imagesLoaded.makeJQueryPlugin( $ );
// now use .imagesLoaded() jQuery plugin
$('#container').imagesLoaded( function() {...});
```

Run webpack.

```bash
webpack main.js bundle.js
```

### RequireJS <a href="#requirejs" id="requirejs"></a>

imagesLoaded works with [RequireJS](http://requirejs.org/).

You can require [imagesloaded.pkgd.js](http://imagesloaded.desandro.com/imagesloaded.pkgd.js).

```js
requirejs( [
  'path/to/imagesloaded.pkgd.js',
], function( imagesLoaded ) {
  imagesLoaded( '#container', function() { ... });
});
```

Use `.makeJQueryPlugin` to make `.imagesLoaded()` jQuery plugin.

```js
requirejs( [
  'jquery',
  'path/to/imagesloaded.pkgd.js',
], function( $, imagesLoaded ) {
  // provide jQuery argument
  imagesLoaded.makeJQueryPlugin( $ );
  // now use .imagesLoaded() jQuery plugin
  $('#container').imagesLoaded( function() {...});
});
```

You can manage dependencies with [Bower](http://bower.io/). Set `baseUrl` to `bower_components` and set a path config for all your application code.

```js
requirejs.config({
  baseUrl: 'bower_components/',
  paths: { // path to your app
    app: '../'
  }
});

requirejs( [
  'imagesloaded/imagesloaded',
  'app/my-component.js'
], function( imagesLoaded, myComp ) {
  imagesLoaded( '#container', function() { ... });
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/javascript/kiem-tra-hinh-anh-da-duoc-tai-voi-thu-vien-imagesloaded-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
