Why server side HTML rendering?
Why do server side HTML rendering? Is that a throw back from the days when there were few web standards and desktops were slow and and could not handle complex DOM manipulations? Why not make Ajax calls to get JSON and inject the data directly into the page? Why not let the the JavaScript handle translating data into HTML? Why should modern web application development continue to rely on server side HTML rendering instead of pushing that to the client?
JavaScript as the render engine
As a test I created a site where all of the dynamic content was rendered by JavaScript. The basic concept is simple- create an HTML template where content could be injected into the page. The page contains HTML elements with ids. The Ajax calls create JavaScript objects (thank you JSON). Now inspect the JavaScript object to see if any of the properties match the ids of the HTML elements. If we find a match, inject the data into the innerText, value, src or href of the DOM element. Simple.
var data = {"name":"Bugs Bunny", "email":"bbunney@bugs.com"};
<div>
<p id="name"> </p>
<p id="email"> </p>
</div>
The page inspects the object and the HTML and injects the data into the DOM.
<div>
<p id="name"> Bugs Bunny </p>
<p id="email"> bbunney@bugs.com </p>
</div>
//obj is a JavaSript object
for (propertyName in obj) {
if (obj.hasOwnProperty(propertyName) && typeof obj[propertyName] !== "function") {
//Get the DOM element
var property = container.querySelector("#" + propertyName);
if(property != null)
property.innerHTML = obj[propertyName].toString();
//set the innerHTML
}
}
So how did that work out for you?
Great. But I don't think I achieved the time savings I was wanting to get. I was expecting this technique to drastically reduce dynamic page development time. I believe this was a significant improvement over the old ASPX webforms days. This approach allowed me to make an Ajax call and let the page essentially inspect the returned object and update itself. But I am not sure it is much better than ASP.NET MVC (in respect to development time). I also found myself having to put special logic into the page to treat data differently. So each page type ended up with its own "special rendering rules".
Would I use it in Production?
Most definitely. This is a nice tool to have in the tool kit. But as with anything, the right tool for the right job.