Last Updated: February 25, 2016
·
1.191K
· gogocat

Durandal JS - Preload templates

I have been using Durandal JS for a while and I think it is a fantastic framework.

However it lacks of option to preloading templates for fast view render. Probably because Durandal is using RequireJs text plugin for template loading.

So I modified the text.js

Download example here

The change was surprisingly simple and without breaking Durandal's binding life cycle.

An example of preloading the shell template on the index.html

<script type="text/html" data-view-path="app/views/shell.html"> 
... template content...
</script>

Text.js will now check if the request template is present on the page, otherwise will do the ajax call.

The attribute "data-view-path" defines as the same request path of the template.

text.js is AMD module, which mean it is protected within the returned module. So i can't do a AOP magic to dynamically modified the module.

So here are the change to the text.js file. Yes, the change require jQuery.

1. Add

    var  $textHtml = []; // for cache all text/html elemets

2. add

    $(document).ready(function() {
        $textHtml = $("[type='text/html']");
    });

3. updated text.get (around line 263)

var dataTmp = ($textHtml.length) ? $textHtml.filter("[data-view-path='"+ url +"']").eq(0) : [],
       xhr,
   header;

    if (dataTmp.length) {
          return callback(dataTmp.html());
    }
        ....

Now the key benefits are
- Reduce amount of ajax calls
- Leverage of server side language data binding. In my case, I can use .Net MVC partial with Model data on the template.

1 Response
Add your response

I'm working with a java server side. So I can make a jsp include within your data-view-path, that's just the perfect trick, thanks.

over 1 year ago ·