Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created December 15, 2011 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/1481201 to your computer and use it in GitHub Desktop.
Save barneycarroll/1481201 to your computer and use it in GitHub Desktop.
Wait for all elements with external resources (imgs, iframes) in current $ scope to have loaded before firing passed function
/*
Wait for all elements with external resources (imgs, iframes)
in current $ scope to have loaded before firing passed event.
e.g.
$('.plugin img').loadAll(function(){...})
For a version of $().load that forces a reload (if load has already
fired before event binding), use
$('.plugin img').loadEach(function(){...})
Downside to this is that to ensure the load event fires,
an extra HTTP request will be made if the resource has already loaded
*/
(function($){
$.fn.loadAll = function(f){
var
$this = this,
$el = this.filter(function(){
return this.hasAttribute('src') && !/^data:/.test(this.src)
}),
count = 0;
$el.load(function(){
++count && count === $el.length && f.apply($this)
});
$el.each(function(){
this.src += '?loadAll'
});
return this;
};
$.fn.loadEach = function(f){
var count = 0;
this.each(function(){
var $el = $(this);
f.apply($el, count);
});
return this;
};
}(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment