imagesLoaded - JavaScript is all like "You images done yet or what?"

Related tags

Effect imagesloaded
Overview

imagesLoaded

JavaScript is all like "You images done yet or what?"

imagesloaded.desandro.com

Detect when images have been loaded.

Install

Download

CDN

">
<script src="https://unpkg.com/imagesloaded@5/imagesloaded.pkgd.min.js">script>

<script src="https://unpkg.com/imagesloaded@5/imagesloaded.pkgd.js">script>

Package managers

Install via npm: npm install imagesloaded

Install via Yarn: yarn add imagesloaded

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 object. 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.

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

// 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.

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

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

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

// 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 or vanilla JS demo on CodePen.

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

// 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 or vanilla JS demo on CodePen.

Events

always

// 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

// 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

$('#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

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

Properties

LoadingImage.img

Image - The img element

LoadingImage.isLoaded

Boolean - true when the image has successfully loaded

imagesLoaded.images

Array of LoadingImage instances for each image detected

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 );
  }
});

Webpack

Install imagesLoaded with npm.

npm install imagesloaded

You can then require('imagesloaded').

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

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

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

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

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

Run webpack.

webpack main.js bundle.js

Browserify

imagesLoaded works with Browserify.

npm install imagesloaded --save
var imagesLoaded = require('imagesloaded');

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

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

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

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

Browser support

  • Chrome 49+
  • Firefox 41+
  • Edge 14+
  • iOS Safari 8+

Use imagesLoaded v4 for Internet Explorer and other older browser support.

Development

Development uses Node.js v16 with npm v8

nvm use

MIT License

imagesLoaded is released under the MIT License. Have at it.

Comments
  • Firefox 18 OSX and Win7 loaded-event triggered before image is loaded.

    Firefox 18 OSX and Win7 loaded-event triggered before image is loaded.

    I'm not sure if I'm doing something wrong or if something is going on in Firefox on this page: http://fl.chrisjohansson.com/gallery/lega-figure/ (and it's siblings).

    The summary is: I hide an image, show a loader, switch out the img src, run imagesLoaded and show the image again. This works splendidly in all tested browsers.

    However, it seems firefox is triggering events before the image is loaded. So while it's doing all that it should it's not actually waiting for the image to load. It reminds me of some issue I think I read somewhere about it thinking an image is cached when it isn't. I'm just not good enough at debugging to be able to pinpoint that.

    It works in all other tested browsers.

    Thanks!

    opened by cjohansson52 50
  • IE occasionally aborts image load

    IE occasionally aborts image load

    We're using imagesloaded in a lazy-loading widget. A few of the initial images have hard coded src, the rest are inserted lazily from a data-src attribute. On IE9, the Network Developer tab shows the lazy images aborting on the first attemp and then immediately reloading successfully. However, the hard-coded images occasionally abort as well, and never get loaded. This happens irregularly, sometimes reloading with a clear cache 30 times before it happens again.

    I can't reproduce the problem when I remove imagesloaded (the src is otherwise untouched for them). So far, I've been unable to reproduce it on JSFiddle http://jsfiddle.net/bluescrubbie/VxFb4/12/.

    I know it's obscure, but I thought I'd let you know.

    ie 
    opened by bluescrubbie 38
  • Bugs appending new elements (Infinite scroll + Masonry / Isotope)

    Bugs appending new elements (Infinite scroll + Masonry / Isotope)

    Several users have had problems with past versions of imagesLoaded (pre v1.1.0) and Infinite Scroll with Masonry or Isotope. If you're having trouble as well with these, please speak up.

    This issue tracker will collect the previous issues held in Masonry and Isotope.

    opened by desandro 31
  • jQuery.imagesLoaded does not work with FireFox

    jQuery.imagesLoaded does not work with FireFox

    screen shot 2015-04-30 at 12 11 07 pm

    Note: I didn't just "quickly take a screenshot". I waited for about a minute or so (in the meantime I moved the "about windows" in view). The images are never loaded

    Note 2: In the screenshot it looks like no images are loaded at all. That's not true either. I just moved the "about windows" on top of the loaded images accidentally.

    On not that good networks ( that's what the network link conditioner is there for ) imagesLoaded just stops trying to load the images at all. No 'fail', no 'always', it just stops and does nothing.

    I used this for the screenshot: http://codepen.io/desandro/pen/bIFyl

    imagesLoaded vanilla version works just fine with firefox and problematic network. For some reason the jQuery version is what causes problems.

    opened by pyronaur 22
  • Add srcset support

    Add srcset support

    Using the recommended markup (http://www.filamentgroup.com/lab/to-picturefill.html) for <img> with srcset while using picturefill seems to break imagesLoaded on browsers with native support for srcset. Let's say I have an image like

    <img srcset="image-400.jpg 400w,
                 image-800.jpg 800w,
                 image-1600.jpg 1600w"
    >
    

    We don't use src here to avoid loading two images. Then we use use picturefill for browsers that don't support srcset natively.

    In both browsers with and without native support (thanks to picturefill) the right image is loaded, but imagesLoaded reports the image broken on browsers with native support (resulting in not being able to fade the image in smoothly when loaded)

    Check out this reduced test case on latest Firefox (v.35: working) and Chrome (v.40: broken): http://codepen.io/superstructure-net/pen/EaWvZv/

    Any ideas? Thx!

    feature request 
    opened by hatsumatsu 22
  • IE compatibility

    IE compatibility

    hi, first thanks for this great plugin.

    It seems to work in IE sometimes, but not always (esp in IE8 but also 9). Seems IE gets tripped by the set to blank "hack" (it is a hack for webkit AFAIU, is it not?). I added an IE check (I know not good practice but the hack seems for webkit and maybe should stay for webkit only) and only if not do the "this.src = blank;" thing. Firefox does not seem to bother either way by the way...

    I had the IE problem specifically with http://tympanus.net/codrops/2011/09/05/slicebox-3d-image-slider/ which includes the imagesloaded plugin but even after update to newest was most of the times failing (the demo seems to work but on a busier page it mostly did not).

    If you want I can add the complete code.

    Have you run into such an issue somewhere? I tested under Windows 7 64bit IE9 and 7/8 compat mode settings.

    Thanks!

    opened by cthedot 21
  • Fix image.useCached function when width is not set in Chrome in very fas...

    Fix image.useCached function when width is not set in Chrome in very fas...

    I had an issue on Chrome in a very fast environment (using masonry) The cached image was triggering confirm event before having their naturalWidth set. In my case, this issue was causing bad visual issue.

    Adding a setTimeout until the naturalWidth is here solves the problem for me.

    In case the naturalWidth is already here, nothing is change as no setTimeout is used.

    opened by nyroDev 18
  • Built File Doesn't Work w/ AMD

    Built File Doesn't Work w/ AMD

    The packaged versions of the script don't work with AMD loaders because, even though they define the dependencies ('eventEmitter' and 'eventie'), they aren't registered with a name.

      define( [
          'eventEmitter',
          'eventie'
        ],
        defineImagesLoaded );
    

    So when this point is reached, the loader doesn't know where to find either of them.

    opened by matthewwithanm 18
  • Loaded Images Have Zero Height and Width

    Loaded Images Have Zero Height and Width

    I'm trying to use this script to determine when images have finished loading so that I can draw the images to an html5 canvas.

    In the 'always' callback, the image usually (not always) has a width and height of zero, which makes it impossible to set the canvas to the proper size or to draw the image with the correct parameters.

    Here is the code (coffeescript):

    https://gist.github.com/564ccd4410e1fccc8cb9

    opened by lynndylanhurley 16
  • Bugs in Firefox 3.6

    Bugs in Firefox 3.6

    In demo page here http://desandro.github.com/imagesloaded/ broken images counter does not work in Firefox 3.6, also I have bugs in FF3.6 in my current project (script assuming that image is loaded before image is actually loaded), but for now I can`t make a proper test case.

    upd: I also noticed, that with original script from gist here https://gist.github.com/268257 the bugs from my project are gone in FF3.6 and 10. Still can`t reproduce a bug in a small test case.

    opened by andreyvolokitin 16
  • Add method to abort loading

    Add method to abort loading

    It would be nice to have a method to abort loading so a callback is never reached, something like:

    var loading = new imagesLoaded( elem, callback );
    loading.abort();
    
    feature request 
    opened by staaky 14
  • Warning: noob incoming

    Warning: noob incoming

    Hi Desandro,

    I am building my first website using wordpress and its been a long journey this year learning everything. I am now trying to optimize my website because it was ofc poorly built by me, since I started January as a total noob, and with so many plugins that I think people like you would shed a tear how bad it is. However perfmatters plugin let me delay some JS to keep it atleast decent. I am trying to understand it all and analyze using pagespeed insights to see what I can fix. In doing this your build is showing. I just wonder what/how its added to my website and if I should not be concerned? I am lazyloading with perfmatters so I dont really know what this does:

    mydomain.com/wp-includes/js/imagesloaded.min.js?ver=4.1.4

    Sorry to disturb you.

    Best regards,

    Flamur

    opened by flamuren 0
  • obj is not iterable

    obj is not iterable

    After updating this script from 4.1.0 to 5.0.0 without any changes of initialization code, it's now thrown error and doesn't work:

    Uncaught TypeError: obj is not iterable

    Initialization code:

    $('.js-b').each(function () {
        console.log($(this));
        $(this).imagesLoaded().done(function () {
          ...
        });
    });
    

    console.log => Object { 0: div.all-b.vertical-b.js-b, context: div.all-b.vertical-b.js-b, length: 1 }

    opened by Craigy- 1
  • Downloads jpeg image when using picture element in browser that supports modern formats

    Downloads jpeg image when using picture element in browser that supports modern formats

    I am using vue-masonry which uses this package (I have 4.1.4 of this package installed). It seems this pacakage is causing jpeg images to be downloaded when I am using a picture element with webp and jxl sources. As a result, both the webp image and the jpeg image get downloaded, somewaht losing the benefit of using the modern formats.

    opened by muster-mark 0
  • Imagesloaded v5 triggers loading of largest image when using srcset

    Imagesloaded v5 triggers loading of largest image when using srcset

    Hi desandro! wordpress uses SRCSET attribute for responsive images. When I use imagesloaded It triggers the download of the largest image generating extra bandwidth. Am I doing something wrong? Is there a way of triggering imagesloaded on the size that the browser requests from the srcset? thanks!

    edit:

    I'm using imagesloaded@5

    opened by arjhun 3
  • Some issues -

    Some issues -

    Hi this is a great library however I have some problems with version 5.0.0:

    • progress event not fired, I can't trigger each image that is loaded.
    • broken link of CSS background image not trigger in fail event??
    <div id="event-galleries-page">
        {{!-- Broken <img> for testing --}}
        <div class="grid-item bg t2">
            <div class="grid-item-img-container">
                <div class="grid-item-img">
                    <img src="assets/images/dummy/event-galleries/12x.jpg">
                </div>
            </div>
        </div>
        {{!-- Broken CSS BG for testing --}}
        <div class="grid-item bg t2">
            <div class="grid-item-img-container">
                <div class="grid-item-img" style="background-image: url(assets/images/dummy/event-galleries/2x.jpg)"></div>
            </div>
        </div>
        <div class="grid-item bg t4">
            <div class="grid-item-img-container">
                <div class="grid-item-img" style="background-image: url(assets/images/dummy/event-galleries/11.jpg)"></div>
            </div>
        </div>
    </div>
    
        const imgLoad = imagesloaded('#event-galleries-page', { background: true });
        imgLoad.on('always', ( instance ) => {
            console.log('all images loaded');
        });
        imgLoad.on('done', ( instance ) => {
            console.log('all images successfully loaded');
        });
        imgLoad.on('fail', ( ) => {
            console.log('all images loaded, at least one is broken');
        });
        imgLoad.on('progress', ( instance, image ) => {
            const result = image.isLoaded ? 'loaded' : 'broken';
            console.log( 'image is ' + result + ' for ' + image.img.src );
        });
    

    From the above HTML code, when the broken JPG exists, the "always" event is not fired which is correct. However when I took out it so that only all CSS background images are used, but only one CSS BG is broken, the fail event was not fired.

    Screenshot 2022-08-10 at 01 16 04

    And the progress event never got fired.

    Hope someone can help.

    Thanks.

    opened by codyng 0
  • wp + masonry + imagesloaded lazyload = gap between posts

    wp + masonry + imagesloaded lazyload = gap between posts

    Hi,

    I use a customized version of the Wordpress theme Baskerville, which uses jetpack masonry and imagesloaded lazyload.

    But when it loads new posts after scrolling, there is a gap between the posts. See it here: https://www.infolibertaire.net/ Screenshot: https://prnt.sc/l2vzru-dk5rY Main javascript: https://infolibertaire.net/wp-content/themes/baskerville/js/global.js

    If I open chrome developer console and manually type $blocks.masonry(); it fixes the issue... until I scroll down further and the layout breaks again

    Any idea how I can fix this issue?

    So far I found this workaround:

    time=setInterval(function(){
       $blocks.masonry();
     },5000);
    

    But it is not ideal as users can still see the glitch for a few seconds before the posts move

    opened by Ungov77 1
Releases(v4.1.4)
  • v4.1.4(Jan 2, 2018)

  • v4.1.1(Oct 27, 2016)

  • v4.1.0(Jan 15, 2016)

  • v4.0.0(Dec 28, 2015)

  • v3.2.0(Oct 29, 2015)

    • Added new feature, detect when background images have loaded with { background: true }. #29
    • Removed cache. Was unreliable and buggy. #103, #115, #206
    • Address Firefox bugs by checking for load event on current img. #50, #191
    • add .makeJQueryPlugin() for better compatibility with jQuery and Browserify/RequireJS/Webpack. #180
    • README/site improvements
      • Add Webpack instructions. #203
      • jQuery first
      • Site nav
    • Move to Gulp
    • Update Qunit v1.20
    Source code(tar.gz)
    Source code(zip)
Owner
David DeSandro
Designer, developer @metafizzy
David DeSandro
Animated images that are superficially attractive and entertaining but intellectually undemanding. Cool as all hell though!

MMM-EyeCandy Animated images that are superficially attractive and entertaining but intellectually undemanding. Add some EyeCandy to your mirror. Some

Mykle 36 Dec 28, 2022
Javascript library enabling magnifying glass effect on an images

Magnifier.js Javascript library enabling magnifying glass effect on an images. Demo and documentation Features: Zoom in / out functionality using mous

Mark Rolich 808 Dec 18, 2022
A simple yet powerful native javascript plugin for a cool typewriter effect.

TypewriterJS v2 NPM Repository JSFiddle Example Emoji Example CDN You can use the CDN version of this plugin for fast and easy setup. <script src="htt

Tameem Safi 1.8k Jan 4, 2023
"shuffle-text" is JavaScript text effect library such as cool legacy of Flash.

ShuffleText This is the JavaScript library for text effect such as Flash contents. Setup Script Install <script src="shuffle-text.js"></script> NPM In

Yasunobu Ikeda 96 Dec 24, 2022
:keyboard: Simulate a typewriter effect in vanilla JavaScript.

malarkey Simulate a typewriter effect in vanilla JavaScript. Flexible API allowing granular control Option to repeat the sequence indefinitely Allows

Yuan Qing Lim 237 Nov 18, 2022
Enterprise-grade JavaScript snow effect for the internets, setting CPUs on fire worldwide every winter since 2003.

/** * DHTML Snowstorm! JavaScript-based Snow for web pages * -------------------------------------------------------- * Version 1.44.20131208 (Prev

Scott Schiller 518 Dec 24, 2022
Small but good javascript smoke effect 🌬💨

Demo You can play with a live demo here → Installation Basic Copy the smoke.js file into your project and use it with a script tag: <script src="smoke

Guillermo Webster 239 Dec 28, 2022
Pure CSS (no JavaScript) implementation of Android Material design "ripple" animation

Pure CSS ripple effect (no JavaScript) CSS-only implementation of Android Material design "ripple" animation on click event Main advantage of this sol

Mladen Plavsic 334 Dec 11, 2022
Javascript and SVG odometer effect library with motion blur

SVG library for transitioning numbers with motion blur JavaScript odometer or slot machine effect library for smoothly transitioning numbers with moti

Mike Skowronek 793 Dec 27, 2022
Cool and powerful effect to select fields. Javascript vanilla and ~2kb gzipped

pickout Cool and powerful effect to select fields. Javascript vanilla and ~2kb gzipped. DEMO PAGE For syntax of the previous version click here How to

Alan Ktquez 89 Sep 20, 2022
Javascript Sound Effect Generator

This is a JavaScript library for sound effect generation and is supported on most current browsers. Generation speed is approximately 1s audio = 10ms

Loov 567 Oct 31, 2022
🎨 Aquarelle is a watercolor effect component. Javascript library by @Ramotion

Aquarelle About This project is maintained by Ramotion, Inc. We specialize in the designing and coding of custom UI for Mobile Apps and Websites. Look

Ramotion 1.8k Dec 9, 2022
Liquideffect - Javascript Library for creating liquid effect on image and RGB effect on mouse direction.

LiquidEffect Javascript Library for creating liquid effect on image and RGB effect on mouse direction. Demo https://liquideffect.netlify.app/ Dependen

Rohail 8 May 6, 2022
A JavaScript library for advanced 2D slideshow with WebGL, that provides variety of beautiful effects

gl-slideshow An advanced 2D slideshow with WebGL, provides a variety of beautiful effects with GLSL power. Shaders are forked from https://gl-transiti

Akihiro Oyamada 68 Nov 28, 2022
Javascript library to draw and animate images on hover

Hover effect Javascript library to draw and animate images on hover. If this project help you, you like this library or you just want to thank me, you

Robin Delaporte 1.5k Dec 23, 2022
A tiny javascript library for obfuscating and revealing text in DOM elements

baffle.js A tiny javascript library for obfuscating and revealing text in DOM elements. camwiegert.github.io/baffle ~1.8kb gzipped âš¡ Dependency-free ?

Cam Wiegert 1.7k Dec 26, 2022
A JavaScript Typing Animation Library

Live Demo | View All Demos | View Full Docs | mattboldt.com Typed.js is a library that types. Enter in any string, and watch it type at the speed you'

Matt Boldt 12.6k Dec 31, 2022
Lightweight and fast Particle library written in JavaScript

Spark Particles Lightweight and fast Particle library written in JavaScript Zero Dependencies! Basic example Installation npm i spark-particles --save

Yury Petrov 11 May 9, 2022
Javascript library to generate an infinite stream or a burst of image based particles on HTML canvas.

spxparticles Stream or a burst of image particles on HTML canvas Simple Javascript library for generating an infinine stream or a burst of image based

Tuomo Kulomaa 3 Dec 3, 2020