I'm currently building a backbone app where I absolutely need some files before proceeding with certain tasks.
For Example:
- the template files for rendering a view
- a
language.json
file that holds the copy for the whole app
Now what I want to avoid is the callback hell that brings me to. Like I could never use this.template(data)
because I always have to check a deferred object / promise if that template is already loaded.
getTemplate: function(path) {
return $.get('/templates/'+path).then(function(src) {
// is the copy already available?
return App.Deferreds.copy.then(function(copy) {
// insert copy into this html string
src = App.Models.Copy.insertCopy(src, copy);
// return a handlebars tempate with copy pre-filled
return Handlebars.compile(src);
});
});
}
So I thought I'd make the AJAX requests for those files synchronous and return the files content instead of a promise.
getTemplate: function(path) {
var template;
$.ajax({
dataType: "json",
url: '/templates/'+path,
async: false,
success: function(src) {
// insert copy into this html string
src = App.Models.Copy.insertCopy(src, copy);
template = Handlebars.compile(src);
}
});
return template;
}
Now chrome is telling me synchronous xmlhttprequest on the main thread is deprecated
. And after researching it it is indeed removed from the specs (or will be).
Now what's my alternative here? How do I load absolutely needed files via JavaScript into a web-app?
It seems odd to use AJAX in the first place when I ALWAYS have to wait for those files.
Seems like you are trying to implement a poor man's dependancy management system. You should consider using an existing one such as RequireJS or Browserify