jQuery.Deferred to Tell When Certain iframes Are Loaded
22 Feb 2011Since jQuery 1.5 came out I’ve been intrigued about the new jQuery.Deferred
feature, but hadn’t used it until now. You might think that Deferreds are isolated to only jQuery.ajax
requests, but they are much more flexible than that. jQuery.ajax
utilize defferds, but you can also use them to define your own set of promises.
<blockquote>Eric Hynds wrote an awesome blog post entitled Using Deferreds in jQuery 1.5 describing the inns and outs of jQuery Deferreds in much more detail, but I thought I’d share a use case that I found helpful in a recent project.</blockquote>I’m working on a project where there are multiple hidden iframes loaded on the page (don’t ask why LOL) and I needed a way to tell if they were all loaded. Almost immediately I thought about using the new Deferred feature!
<pre>(function($) {
function iFrameLoaded( id, src ) {
var deferred = $.Deferred(),
iframe = $( “” ).attr({
“id”: id,
“src”: src
});
iframe.load( deferred.resolve );
iframe.appendTo( “body” );
deferred.done(function() {
console.log( “iframe loaded: “ + id );
});
return deferred.promise();
}
$.when(
iFrameLoaded(“jQuery”, “http://jquery.com”),
iFrameLoaded(“appendTo”, “http://appendto.com”))
.then( function() {
console.log( “Both iframes loaded” );
});
}(jQuery));
</pre>
The above code creates a new jQuery.Deferred
object (line 4) and iframe element. Once the iframe is loaded, we tell the deferred object to resolve
itself (line 10). At that point we define our own event handler to respond to when the deferred is done
(line 13). In this case we just print to the console that “iframe loaded”. Then we return the deferred promise
(line 17) so that we can use it in the new jQuery.when
method.
Next we call the jQuery.when
method (line 20) and pass all the promises we want fulfilled before we proceed. Once all the iframes are loaded, then the then
method will execute (line 23) printing out “Both iframes loaded” to the console.
View Demo Edit Demo
<blockquote>Note: This same concept can also be applied to a set of images loading and many other applications.</blockquote>