Dimitar Christoff
Dimitar Christoff

Reputation: 26165

requirejs loading async templates module pattern

I just decided to try require.js for the first time and for the most part, it works fine - until I get to the point where I try to handle template loading dynamically.

basically, i have a requirement that the app should not proceed until the templates have all been loaded and made available.

to that effect, a module 'templating' has been created. it imports a definition of an array of templates (already available) that it needs to load - require - before it returns.

I am pretty sure this is probably an anti-pattern so how would you fix it?

app -> requires "templating"
    define templating ->
        - loop through an array of templates and dynamically create a list
        - define all templates (via text!) so later we can require("template-name")
        - also tried, require all templates 

What I observe is that the templating module loads and becomes available to the app before all the templates are loaded.

The XHR fetching the templates follows afterwards.

How do i prevent the module from returning before all the texts load and compile? pseudo code or links to examples would be fine.

Upvotes: 0

Views: 385

Answers (1)

John Munsch
John Munsch

Reputation: 19528

We actually had one solution early on in a project and then moved to another one.

[1] Synchronization - Because we're using jQuery in our app we have the jQuery Deferred object available for use throughout the app. I created one instance of Deferred which only had its .resolved() called when all of my templates were loaded. Then each time I tried to use a template I had it wrapped in code like this:

$.when(cache.templatesLoadedPromise).done(
  function () {
    // Render the view.
    $("...").html($.tmpl(cache.template, jsonData));
  });

Then none of the renders would happen until the templates were available.

[2] Per module loading and registration - Nobody was that crazy about solution [1] and we wanted each module to load only the templates needed for that particular module. So we started just listing them as "text!something.tmpl" requirements and then doing a registration of that particular template as the first line within the module that had that as a requirement. In our case, we use Handlebars as the template engine together with ICanHandlebarz (similar to ICanHaz for Mustache). So I have a call to ich.addTemplate("something", something); up at the beginning of the module code.

In a few cases, multiple modules used the same templates so I had to test to see if the template was already registered before doing the registration.

I hope one of those would help you with your problem.

Upvotes: 1

Related Questions