Then you have to include some bulky library that parses these scripts and compiles them to a function that you'll use later. All this happens pretty fast, but not any faster than just using the DOM apis.
I can't find the link, but I believe there is a proposal to standardize client side templating, so hopefully that will make the process a bit cleaner.
//synchronous
body.innerHTML = render('blog.html',data)
//asynchronous
render('blog.html',data,body)
render=function(url,data,obj){
if url in cache: use cache
var http = xmlhttprequest()
http.get(url,obj?async:sync)
http.onready:
parse data in html
if obj: obj.innerHTML = html
else: return html
} <link href="mytemplate.mustache" rel="template" type="text/mustache" onload="showSnippet()" /> <link hef='blog.html' rel='template' id='myblog' defer>
But still, we don't want to load 50 templates at the same time if the app is big then use one or two in that session, that's why loading them on demand with httprequest might be a better solution.*Besides, being static in nature they would be cached on the server and client for instant access.
Use like thus:
var tmpl = document.getElementById('myblog').template;This is still ugly, in that debugging templates is an impossible pain the arse because there's no useful line information. On the plus side they're much easier to read than a chain of DOM manipulations.
It's arguable whether this is "better". I usually have to interact with the DOM programmatically anyway (attaching events, for example), so why not build the DOM in javascript as well?
I realize that templates are a popular choice for many, but I view them as an unneccesary layer of indirection. Sort of like printing out an email, hand writing a response, and scanning it back in as a reply. Once your markup has been converted to a document object model, why not embrace it?
Using a bunch of calls to appendChild() and setAttribute() results in code that is difficult to read, because it's so low-level. You can't "see" the generated HTML, just like in assembly you can't really "see" the code structure.
Whereas using templates lets you "see" your HTML, with an easy-to-understand structure. So it's the natural, default choice for ease-of-use and maintenance.
Myself, I much prefer imperative.
Using html templates is good separation of concerns and js just isn't very good at expressing html structure. Jade would have been a much better choice IMO. Laconic does a good job of minimizing the problems with using js to programatically build dom in js but still doesn't come close to a proper templating language.