Here's a Gist for a little jQuery plugin that adds a loadThen function to a set of jQuery elements. It's basically load() without the callback and it returns a promise that is only resolved after the content is loaded and inserted into the set of selected elements.
It's basically a copy/paste of jQuery's own load() code except it returns the promise from the actual ajax call. This lets you get a rejected promise if the ajax fails.
Since it's based on the load() functionality, you can add a selector after the url seperated by a space to get only a fragment of the loaded html.
Example 1: Load the home page of this site into element with id="container"
$('#container').loadThen('/').then(function () {
// loaded and ready.
}, function () {
// error
});
Example 2: Load the home page's header into this page's header
$('h1').eq(0).loadThen('/ h1').then(function () {
// loaded and ready.
}, function () {
// error
});
Gist contents:
(function ($) {
var _loadThen = $.fn.loadThen;
$.fn.loadThen = function (url, params) {
if (typeof url !== "string" && _loadThen) {
return _loadThen.apply(this, arguments);
}
if(this.length <= 0) {
return jQuery.Deferred().resolveWith(this, ['']);
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if (off >= 0) {
selector = jQuery.trim(url.slice(off));
url = url.slice(0, off);
}
if (params && typeof params === "object") {
type = "POST";
}
return jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params
}).then(function (responseText) {
self.html(selector ? jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) : responseText);
return self;
});
};
}(jQuery));
<div id="c"> <div id="part1"/> <div id="part2"/> ... </div>
– Wellman