Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.