A jQuery plugin that lets you attach callbacks to useful image loading events.

Overview

waitForImages

Copyright (c) 2011-2018 Alexander Dickson @alexdickson

Licensed under the MIT licenses.

http://alexanderdickson.com

Donate!

Build Status

Overview

Provides useful callbacks once descendant images have loaded.

waitForImages also supports both images referenced in CSS, such as the background-image property, and images referenced in element attributes such as srcset. Images referenced in attributes can also be a comma-separated list of images.

It can be useful when WebKit incorrectly reports element dimensions/offsets on document ready, because it has not calculated their descendant img dimensions yet.

Supports all browsers you probably care about.

Get it

You can either grab the source yourself...

...or you can use a hosted version...

Alternatively, you can install with bower...

bower install waitForImages

...or npm...

npm install jquery.waitforimages

Of course, these need to be loaded after jQuery is made available. The current version should be supported by at least jQuery 1.8, or perhaps earlier. If you find incompatibility issues, please check out a previous tagged version.

Usage

There are two ways to use waitForImages: with a standard callback system (previously the only API) or receiving a promise.

Standard

Just provide a callback function and it will be called once all descendant images have loaded.

$('selector').waitForImages(function() {
    // All descendant images have loaded, now slide up.
    $(this).slideUp();
});

You can also use the jQuery promise API.

$('selector').waitForImages().done(function() {
    // All descendant images have loaded, now slide up.
    $(this).slideUp();
});

In the callbacks, this is a reference to the collection that waitForImages() was called on.

Advanced

You can pass a second function as a callback that will be called for each image that is loaded, with some information passed as arguments.

$('selector').waitForImages(function() {
    alert('All images have loaded.');
}, function(loaded, count, success) {
   alert(loaded + ' of ' + count + ' images has ' + (success ? 'loaded' : 'failed to load') +  '.');
   $(this).addClass('loaded');
});

Using the jQuery promises API, you can then use the progress() method to know when an individual image has been loaded.

$('selector').waitForImages().progress(function(loaded, count, success) {
   alert(loaded + ' of ' + count + ' images has ' + (success ? 'loaded' : 'failed to load') +  '.');
   $(this).addClass('loaded');
});

You can also set the third argument to true if you'd like the plugin to iterate over the collection and all descendent elements, checking for images referenced in the CSS (by default, it looks at the background-image, list-style-image, border-image, border-corner-image and cursor properties). If it finds any, they will be treated as a descendant image.

The callback will be called on the successful and unsuccessful loading of the image. Check the third argument to determine the success of the image load. It will be true if the image loaded successfully.

If you want to skip the first argument, pass $.noop or alternatively, pass an object literal to the plugin, instead of the arguments individually.

$('selector').waitForImages({
    finished: function() {
        // ...
    },
    each: function() {
       // ...
    },
    waitForAll: true
});

To use this with the promise API, simply pass one argument, which is waitForAll.

$('selector').waitForImages(true).done(function() {
    // ...
});

You may also set the CSS properties that possibly contain image references yourself. Just assign an array of properties to the plugin.

$.waitForImages.hasImgProperties = ['backgroundImage'];

waitForImages also exposes two custom selectors, img:has-src and img:uncached, (both used in conjunction with the img selector), which allow you to select img elements with a valid src attribute or that are not already cached already by the browser, respectively.

$('img').not(':has-src').remove();
$('img:uncached').attr('title', 'Loading Image');

Feedback

Please use the Issues for any bugs, feature requests, etc.

If you're having problems using the plugin, ask a question on Stack Overflow.

Comments
  • Add a destroy capability

    Add a destroy capability

    I am developing an app Clibu which uses waitForImages. The element containing the images can be removed from the dom, before waitForImages completes. In this scenario I'd like a way to cleanup the img.on('load') event handles that waitForImages adds.

    I've looked through the code and reads the doc's and can't see a way to accomplish this.

    opened by nevf 9
  • 1.6.3 required jquery version problem

    1.6.3 required jquery version problem

    Hey, after the new version 1.6.3 is released, I get a strange version problem for jquery:

    bower install

    Unable to find a suitable version for jquery, please choose one:
        1) jquery#~1.8 which resolved to 1.8.3+1 and is required by waitForImages#1.6.3 
    

    Now I am using jquery 2.1.1 for my project. Can you modify the dependency to accept more recent versions?

    Thanks!

    opened by jesperronn 9
  • selector don't seems to be respected

    selector don't seems to be respected

    I would like to use waitForImages only in a container. There is just one header css background-image inside, load dynamically xith php.

    I check the console, It's seems to work on last version of chrome browser but not on Firefox and Safari. With these too last browser, the callback is execute only after all images on the page are loaded.

    I tried lot of modifications :

    • use an ID for the container instead of Class
    • use the specific hasImageProperties on my background-image div ...

    my code:

    <div class="inner-header" id="inner-header"> <div id="header-cover "class="header-cover cover" style="background-image:url(img.jpg);"></div> </div>

    $('.inner-header').waitForImages({
    
            finished: function() {
                // my callback
                },  
                waitForAll: true
    
            });
    

    Do you have any suggestion ? Thanks for your work.

    Willy

    opened by willybrauner 7
  • Possible to check for % of total loadsize?

    Possible to check for % of total loadsize?

    Hi, Great little tool this - is it possible to get the callback to happen when lets say 50% of the images have loaded? I have a slider with a lot of images - say 70 images in the slider - each 250kb... so waiting till that entire lot has downloaded before starting the carousel is pretty painful on slow connections... Could I use waitForImages to instruct it to wait for 30% of the images to load then allow me to call my custom function to initiate the slider? Any ideas?

    opened by dubbsdubblin 7
  • Doesnt work with css @import neither with dynamic content

    Doesnt work with css @import neither with dynamic content

    I'm trying to use waitForImages in a page with css @import and loading dynamic content with $.ajax() and none of the background images or the img tags of the called page are preloaded.

    opened by BMCouto 7
  • Images are loaded twice when using srcset with width descriptor

    Images are loaded twice when using srcset with width descriptor

    I'm not sure if #64 fixes only srcset attributes that include densitiy descriptors (1x, 2x)?. I use the srcset attribute with width descriptor and the browser always loads two images. E.g. <img src="{url}/s,x,586,y,0/{img_id}" srcset="{url}/s,x,293,y,0/{img_id} 293w, {url}/s,x,440,y,0/{img_id} 440w, {url}/s,x,586,y,0/{img_id} 586w" sizes="(max-width: 520px) 100vw, 15vw" />

    I use the plugin this way: $(element).waitForImages({ finished: function() {...}, waitForAll: true });

    $(element) has two descendant images that should be loaded before some adjustments take place.

    Thanks in advance

    opened by anjanina 6
  • Add support for attributes with images in

    Add support for attributes with images in

    Does as the commit suggests. Has support for attributes, including srcset syntax. Down the line it could be improved to fire a callback when all relevant srcset images have loaded.

    opened by RichieAHB 6
  • $(myImageEl).waitForImages() doesn't work

    $(myImageEl).waitForImages() doesn't work

    It looks like the library works only elements that are children of the selector. Any particular reason? In my case, I prefer waiting only on specific images, so rather than specifying a container, the selector points directly to the image. Unfortunately, waitForImages doesn't find the src in that case..

    // doesn't work
    $('<img src="..." />')
        .appendTo('body')
        .waitForImages()
        .then(function() {
            console.log('executed immediately, because image not detected');
        });
    
    opened by andrejpavlovic 5
  • Wait for images from the same domain only or only for background CSS images

    Wait for images from the same domain only or only for background CSS images

    I use waitForImages to reveal the webpage only after all background CSS and img finish loading. But some images are from other host.

    It would be good to have the following features:

    1. Wait for images from the same domain only
    2. Wait for background CSS images only
    opened by thehappycoder 5
  • waitForImages makes removed images keep downloading

    waitForImages makes removed images keep downloading

    Hi.

    As this plugin creates a stub image element for each matched image and attachs the load event to them, it derives on two undesired (at least from me) events:

    • Images removed from DOM before they are fully loaded keep downloading in the background and consuming useless bandwith
    • The plugin fires loaded events for images that are not on the document anymore

    I could fix this with two keystrokes, but honestly I don't understand why did you take this approach instead of attaching the events directly to the images on the document. Is this a desired effect? Am I missing something?

    opened by moraleja39 5
  • Bower support

    Bower support

    It'd be really nice if I could include waitForImages in my bower.json file. As per my #30 issue, it would be a good idea to make JQuery a requirement with a minimum compatible version.

    opened by Soviut 5
  • Drop jQuery as a prerequisite and provide a jQuery adapter

    Drop jQuery as a prerequisite and provide a jQuery adapter

    I will put this on hold until the native Promise object has good browser support, otherwise I would need to bundle an implementation which would make this plugin larger than required.

    opened by alexanderdickson 2
Owner
Alexander Dickson
Making stuff happen on computers
Alexander Dickson
Piccloud is a full-stack (Angular & Spring Boot) online image clipboard that lets you share images over the internet by generating a unique URL. Others can access the image via this URL.

Piccloud Piccloud is a full-stack application built with Angular & Spring Boot. It is an online image clipboard that lets you share images over the in

Olayinka Atobiloye 3 Dec 15, 2022
BttrLazyLoading is a Jquery plugin that allows your web application to defer image loading until images are scrolled to but not only

BttrLazyLoading.js BttrLazyLoading is a Jquery plugin that allows your web application to defer image loading until images are scrolled to but not onl

Julien Renaux 410 Dec 14, 2022
Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

loading="lazy" attribute polyfill Fast and lightweight vanilla JavaScript polyfill for native lazy loading, meaning the behaviour to load elements rig

Maximilian Franzke 571 Dec 30, 2022
optimize image & upload file to cloud as image bed with tiny image automic.

Rush! 图片压缩 & 直传图床工具 这是一个兴趣使然的项目, 希望 Rush! 能让这个世界的网络资源浪费减少一点点 下载 Downloads 获取最新发行版 功能 Features 拖拽批量压缩图片, 支持格式 jpg/png/gif Drop to optimize, jpg/png/gif

{ Chao } 3 Nov 12, 2022
This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

Jquery-SingleImagePopup This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way

Rajan Karmaker 1 Aug 22, 2022
A simple and useful jquery plugin that allows you to create a Text Area Character Count Effect with limited warning.

jquery-character-counter A simple and useful jquery plugin that allows you to create a Text Area Character Count Effect with limited warning. #Demo Us

Abdoulie Kassama 0 Dec 28, 2020
The progressive image loading library for great good!

AntiModerate The progressive image loading library for great good! Reduce loading time of page to less than a second on slow connections by loading an

Jett LaRue 1.5k Dec 20, 2022
A progressive image loading library. Inspired by Medium’s similar technique.

Blurry Image Load Synopsis A lightweight, zero-dependency library that loads images on demand. Until the images are loaded, a very small version of ea

Dominic Brant 32 Dec 10, 2022
Plugin that lets you create diagrams from textual representation (aka 'Diagrams as Code') within Logseq

Logseq - Diagrams as Code Plugin that lets you create diagrams (and other visualizations) from textual representation (aka 'Diagrams as Code') within

Nicolai P. Großer 80 Dec 21, 2022
An Obsidian plugin that lets you browse the web within Obsidian.

Obsidian Web Browser An Obsidian plugin that allows you to browse the web within Obsidian using v1.0 tabs. The core functionality of the plugin, rende

Dion Tryban 102 Dec 28, 2022
Freewall is a cross-browser and responsive jQuery plugin to help you create grid, image and masonry layouts for desktop, mobile, and tablet...

Freewall Freewall is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nes

Minh Nguyen 1.9k Dec 27, 2022
A jQuery plugin allowing you to scroll an image within a container element

jQuery Scroll Image Inside v0.1 A jQuery plugin allowing you to scroll an image within a container element Usage <div id="window"> <img src="reall

Derek Ashauer 1 Apr 11, 2021
Custom events 'movestart', 'move' and 'moveend' for jQuery.

#jquery.event.move Move events provide an easy way to set up press-move-release interactions on mouse and touch devices. UPDATE 2.0: move events are n

stephband 257 Apr 20, 2022
jQuery based scrolling Bar, for PC and Smartphones (touch events). It is modern slim, easy to integrate, easy to use. Tested on Firefox/Chrome/Maxthon/iPhone/Android. Very light <7ko min.js and <1Ko min.css.

Nice-Scrollbar Responsive jQuery based scrolling Bar, for PC and Smartphones (touch events). It is modern slim, easy to integrate, easy to use. Tested

Renan LAVAREC 2 Jan 18, 2022
adds the *scrollin* and *scrollout* events to jquery, which will fire when any given element becomes (respectively) visible and invisible in the browser viewpori

jQuery.scrolling This plugin adds the scrollin and scrollout events to jquery: these events will fire when any given element becomes visible/invisible

Dark 5 Apr 7, 2021
Fancytree - JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkboxes, drag'n'drop, and lazy loading

Fancytree Fancytree (sequel of DynaTree 1.x) is a JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkb

Martin Wendt 2.6k Jan 9, 2023
A Zotero add-on that scans your Markdown reading notes, tags the associated Zotero items, and lets you open notes for the Zotero items in Obsidian.

Zotero Obsidian Citations Adds colored tags to Zotero items that have associated Markdown notes stored in an external folder. Open an associated Markd

Dae 210 Jan 4, 2023