Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Last active August 29, 2015 14:14
Show Gist options
  • Save hyamamoto/6f8f73a6e520314c7a74 to your computer and use it in GitHub Desktop.
Save hyamamoto/6f8f73a6e520314c7a74 to your computer and use it in GitHub Desktop.
HTML elements with css-class `imgs-onload` will enables `onload` function which is called after all the `<img>` inside the element actually finished loading images.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="jq_imgs_onload.js"></script>
</head>
<body>
<div class='imgs-onload' onload="window.alert('all resources loaded')">
<img src="http://i.imgur.com/PWSOy.jpg" />
<img src="http://i.imgur.com/PWSOy.jpg" />
<img src="http://en.wahooart.com/Art.nsf/O/8XX79N/$File/James-E.-Buttersworth-Clipper-in-a-Heavy-Sea.JPG" />
<img src="http://en.wahooart.com/Art.nsf/O/8XX79N/$File/James-E.-Buttersworth-Clipper-in-a-Heavy-Sea.JPG" />
</div>
</body>
</html>
// Defines `imgs-onload` class which `onload` will be called after all the `<img>` inside the element finished loading images.
var divs = $('.imgs-onload');
divs.each(function (idx, div) {
var imgs = $(div).find("img");
var count = imgs.length;
if (count==0 && div.onload)
div.onload.call(div, count);
var loaded = 0;
imgs.one("load", function (e) {
loaded++;
if (loaded === count && div.onload)
div.onload.call(div, count);
}).each(function () {
if (this.complete) $(this).load();
});
});

jq_imgs_onload.js

Defines imgs-onload class which onload will be called after all the <img> inside the element finished loading images.

Usage

Add imgs-onload class on any HTML element. onload function will be called after image resources fully loaded.

Dependency

  • jQuery >= 1.7.2

License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment