Created
December 15, 2011 14:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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