I am attempting to load a number of small .html files using jQuery, and have them all put into the DOM before I execute a certain part of code. But this is proving extremely difficult. I can make it do ONE file well enough, but anything I try to make it handle multiples just doesn't function and I cannot comprehend why.
This is the code that can do ONE file.
var templates = (function ($, host) {
// begin to load external templates from a given path and inject them into the DOM
return {
// use jQuery $.get to load the templates asynchronously
load: function (url, target, event) {
var loader = $.get(url)
.success(function (data) {
// on success, add the template to the targeted DOM element
$(target).append(data);
})
.error(function (data) {
})
.complete(function () {
$(host).trigger(event, [url]);
});
}
};
})(jQuery, document);
This is used as follows;
templates.load("file1.html",
"#templates-container", "file1-loaded");
$(document).on("file1-loaded", function (e) {
// execute the rest of the page
});
This falls flat if I need to load more than one file though. So I tried this ...
(function ($, host) {
$.fn.templates = function (options) {
var settings = $.extend({
queue: [],
element: this,
onLoaded: function () { }
}, options);
this.add = function (url) {
settings.queue.push(url);
return settings.element;
}
this.load = function () {
$.each(settings.queue, function (index, value) {
$.get(value).success(function (data) {
$(settings.element).append(data);
});
});
settings.onLoaded.call();
}
return settings.element;
}
})(jQuery, document);
Which is intended to work like this ...
$('#templates-container').templates({
onLoaded: function () {
// execute the rest of the code
}
}).add('file1.html').add('file2.html').done();
But it just outright fails, and it gives me no indication as to why. I don't even get an error message. But the onLoaded never gets called properly.