Alternatives to synrchonous AJAX calls for absolute needed files?

84 Views Asked by At

I'm currently building a backbone app where I absolutely need some files before proceeding with certain tasks.

For Example:

  1. the template files for rendering a view
  2. 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.

1

There are 1 best solutions below

1
On

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