Good practices for writing HTML in Javascript - javascript

I was wondering about this if people have strong opinions about the best way to generate HTML on the fly, especially with Ajax based applications.
Do you just create the HTML code using server side scripting and then send it out to the page or perhaps just return a JSON string and let Javascript do the job.
In my personal opinion, the first way ties the presentation layer way too much to the logic and makes it harder to change and a nightmare to maintain. The second way, although is my preferred method, also becomes a nightmare to maintain when the complexity of the project grows.
I was thinking of using a Javascript templating system as another layer, just to make the code more robust and less rigid. Anyone has good ideas of a light and really good JS templating system?

http://ejohn.org/blog/javascript-micro-templating/ is a devilishly brilliant hack for this. End result is very clean.

I too prefer a JSON response with client-side HTML creation logic.
Unfortunately, most real-world client-side HTML writing scripts are broken, containing many HTML-injection flaws that can easily become cross-site-scripting security holes. I think the belief is that because you're talking to your own server rather than directly to a hostile user you're somehow ‘safe’ and can get away without correctly strings when interpolating them into HTML. Which is of course nonsense.
I always see stuff like:
$('#mydiv').append('<em>Deleted '+response.title+'!</em>');
or:
mydiv.innerHTML= '<p>Renamed to '+response.name+'</p>;
or indeed Resig's microtemplating hack, where there is no HTML-escaping done by default. Come on, people! We've only just started cleaning up the legacy of broken PHP scripts serving up server-side XSS, now you want to introduce a whole new massive range of client-side XSS exploits?
Sigh. That's the Lure Of Strings. We think we understand them and can sling them together willy-nilly. But strings are treacherous, with hidden contexts and escaping requirements. If you must generate HTML on the client side you will need a function like this:
function h(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
mydiv.innerHTML= '<p>Renamed to '+h(response.name)+'</p>;
But personally I prefer DOM methods. Like with parameterisation for SQL, using the DOM methods takes the string-slinging out of the equation by talking raw strings directly to the components that will consume them. OK, the problem with the DOM is that it's rather verbose:
var p= document.createElement('p');
p.appendChild(document.createTextNode('Renamed to '+response.name))
mydiv.appendChild(p);
But you can always define helper functions to cut down on that, eg.:
mydiv.appendChild(makeElement('p', {}, 'Renamed to'+response.name));
(The new element creation stuff in jQuery 1.4 uses a similar style.)

+1 year ago, we started a new web app, and needed a way to render HTML from JSON data, in the browser.
We wanted it as fast as an XML/XSLT transformation.
Our answer to that was the JS template engine PURE.
Unlike most of the JS templating libs around, it keeps the HTML untouched(no strange tags at all) and except a few notations, it doesn't bring a new language to learn, only JS and HTML.
The way I use it:
Build the static HTML directly in the page
Then add the JS logic step by step, and the HTML becomes alive progressively
Once you get used to it, both HTML and JS can have a safe separate development life, and can be split between a designer and a JS developer job

We had a system where a lot of data was being passed as JSON from the server and then handled through a javascript templating engine on the client side. In .Net 4.0 (maybe even 3.5 sp1, i am not sure), this can be done using Client Templates.
I would prefer passing JSON over sending html. Its always good to keep data and view separate.

If you want to preserve the MVC framework, you should let your template framework do the templating.
The AJAX should only perform the server request, which performs all DB and business logic and then returns the URL to the template that should be loaded.

Related

Using math in browser using XML data

I'm trying to make pull XML or Csv data into a HTML file then I want to use math to add up the values and show the result on the page ( I'm basically trying to display invoices on a web browser)
My skill set is HTML/CSS and I understand a little JavaScript
I've managed to pull XML data into HTML using http request and style that information using xslt
Really what I'm asking is what is the best solution to my needs is it using the above method then using xquiry to add up values or would I need to learn a bit of Ajax, Json and calculate the values with JavaScript?
You really should learn AJAX in order to fetch and manipulate data instead of fetching presentation parts. That's the way everyone follows as it allows more responsive interactions with the user and a cleaner architecture in case of complex interactions.
But that doesn't mean you must abandon XML : originally AJAX was built on XML (the X in AJAX) and not JSON.
Personally I prefer JSON, and I think it will be easier to manage in the long term, but if the server side is hard to change, you can fetch the XML (look for example at jquery's ajax function), build javascript objects using it, and then change your screen using those data. If later you decide to use JSON instead of XML, you'll just have to change the "parsing" part of the client code.
"I'm trying to make pull XML or Csv data into a HTML file then I want to use math to add up the values and show the result on the page"
You can do this with either XSLT or javascript. However, with XSLT things can become pretty complicated, depending on what version you're using. XSLT 1.0 has pretty limited set of functions for aggregating results. For all XSLT, you can't reassign variables you'll have to solve many of these things with recursion. In my opinion, not really a comfortable method.
Regardless of the choice between XSLT and Javascript, I would also question the architecture that would put this kind of logic in the presentation layer in the browser. I think it would be better if the server side would perform all the calculations that are required, and limit the browser's tasks to styling the output.

create html elements on the serverside VS get data as JSON and create tags with javascript

I want to create a AJAX search to find and list topics in a forum (just topic link and subject).
The question is: Which one of the methods is better and faster?
GET threads list as a JSON string and convert it to an object, then loop over items and create a <li/> or <tr>, write data (link, subject) and append it to threads list. (jQuery Powered)
GET threads list which it wrapped in HTML tags and print it (or use innerHTML and $(e).html())
Thanks...
I prefer the second method.
I figure server-side you have to either convert your data to JSON or html format so why not go directly to the one the browser understands and avoid having to reprocess it client-side. Also you can easily adapt the second method to degrade gracefully for users who have disabled JavaScript (such that they still see the results via standard non-JS links.)
I'm not sure which way is better (I assume the second method is better as it would seem to touch the data less) but a definitive way to found out is try both ways and measure which one does better.
'Faster' is probably the second method.
'Better' is probably subjective.
For example, I've been in situations (as a front end dev) where I couldn't alter the html the server was returning and i wished they would have just delivered a json object so i could design the page how i wanted.
Also, (perhaps not specific to your use case), serving up all the html on initial page load could increase the page size and load time.
Server generated HTML is certainly faster if the javascript takes long time to process the JSON and populate the html.
However, for maintainability, JS is better. You can change HTML generation just by changing JS, not having to update server side code, making a delta release etc etc.
Best is to measure how slow it really is. Sometimes we think it is slow, but then you try it out in real world and you don't really see a big difference. You might have the major delay in transmitting the JSON object. That delay will still be there and infact increase if you send an html representation from the server.
So, if you bottleneck really is parsing JSON and generating html, not the transmission from server, then sending html from server makes sense.
However, you can do a lot of optimization in producing the html and parsing JSON. There are so many tricks to make that faster. Best if you show me the code and I can help you make a fast JS based implementation or can tell you to do it on the server.

Server-side ruby vs client-side js api speed/organization

Say I have certain string attributes of an AR object, 'filename' and 'title' for instance, and the way I wish to dynamically fill in a select box on the front end is to ajax in the JSON representation of this object and either display the title attr as the select option's text if it exists, or use the filename attr as the select option's text if the title attr is blank. Now, should I be doing the this-else-that logic I just described on the server-side and returning it w/in my object's JSON representation as something like a 'display_name' attr, or should I be returning the vanilla as_json representation of the object w/ only the AR attrs included and let the js make the decision whether to display the title attr or the filename attr as the select option's text? From what I can tell, JS is much faster than ruby, but at the same time, it seems more maintainable to have this logic on the server-side. I'd also like to know, in general, is executing logic faster on the client side w/ js, or on the server-side w/ ruby? Thanks!
You really shouldn't have to worry about speed too much here - it's highly unlikely that you are really going to suffer from performance problems caused by if/else statements unless you're doing something wrong.
Instead, go for clarity and simplicity. In this case, that probably means rendering the pages on the server directly, unless the data is already in JSON for some reason.
My recommendation is to put logic where it belongs. If the logic is about presentation/rendering, then I would put it in your presentation layer. From your description, this seems to be your client-side JS.
I recommend you keep your APIs agnostic of how their data is rendered/presented as much as possible. This will allow you to change your views without having to also change the structure of the payload returned by the APIs.
In my experience, presentation layers tend to change more often than the underlying structure of the data they present.
I agree with the previous answer, I wouldn't worry about speed here, and go for clear separation of concerns.

Is returning HTML directly for an Ajax response best avoided?

I'm starting to do some JS/HTML/CSS. From looking around, it seems that it's not unusual to return HTML from the back-end (for example, an Ajax response) and directly display it (such as by assigning it to an element's innerHTML). For example, I believe that the jQuery load() method basically is a shortcut to do this.
Taking the approach worries me for a couple of reasons, but I'm not sure if it's just that I'm not familiar with the approaches and idioms in these areas and I am just behind the times or whether these are legitimate concerns. My concerns specifically are:
1) It seems insecure to directly assign HTML to an element. Or, at a minimum, dangerous at least if there's a possibility of any user content (or even third-party content).
2) Sending presentation information (HTML) directly seems like it could likely lead to presentation/model mixing that is best avoided. Of course, it would be possible to have these cleanly separated on the back-end and still return HTML, but on the handful of projects that I've seen that hasn't been the case.
So, my question is, is returning HTML a legitimate form of HTTP response in an Ajax app or is it best avoided?
I don't see right or wrong way to do this, it depends on the ammount of data you are sending and how fast you want it rendered. Inserting HTML directly is faster than building elements from JSON or XML. XSS should not be an issue because you should be escaping user data regardless of the format you're sending it in.
If you take a look at Facebook, all XHR responses (as far as I saw, I only started looking when I saw your question :) are something like:
for (;;);{"__ar":1,"payload":"\u003cdiv class=\"ego_column\">\u003cdiv
class=\"ego_section\">\u003cdiv class=\"uiHeader uiHeaderTopAndBottomBorder
mbs uiSideHeader\">\u003cdiv class=\"clearfix uiHeaderTop\">\u003ca
class=\"uiHeaderActions rfloat\" href=\"http:\/\/www.facebook.com\/campaign\
/landing.php?placement=advf2&campaign_id=368901427978&extra_1=auto\">
Create an Ad\u003c\/a>\u003cdiv>\u003ch4 class=\"uiHeaderTitle\">Sponsored
\u003c\/h4> [...]" }
Their AJAX is content-heavy, so it probably pays off for them to send HTML. Probably their achitecture deals with structure-presentation separation.
I think it depends on the use case to be honest. There is a fairly heafty penalty to be paid on the client if it has to construct a lot of HTML based on some JSON or XML data.
Personally I use a mixture of both - if it's just a small bit of data (an integer or a small string) I'll use JSON or even just the raw data on its own.
If its a complicated set of data (say a bunch of user comments) that I'm going to have to format on the client side then I'll just send the html and save the client the work.
Personally I wouldn't worry about security, at least not users injecting malicious HTML - you should be dealing with that when it's submitted anyway.
Edit: There is an exception to this - when bandwidth is a concern (mobile web, for instance) then sending as little data over the wire is nearly always best.

How to do localizable javascript?

I have a web application that uses TONS of javascript, and as usual, there are a lot of textual constants that will be displayed to the user embedded in the code itself.
What do you think is the best way to make this localizable?
I know I need to take those strings off of the code and replace them with constants, which will be defined into some external place.
For the server side, ASP.Net provides some very neat capabilities for dealing with this.
What's the best to do this in Javascript?
The best idea I have is to have a JS file with ALL the string constants of the JS of the site (i'd have different copies of this, for each language), and then on each page, I include this script first, before all the others.
This seems like the most centralized way, that also wastes the least bandwidth.
Are there any other better approaches?
Thanks!
here's how we did it (in ASP.net), pretty much along the lines of what you've mentioned:
1) Created two javascript files: one which defines all javascript functions/DOM manipulations as required by the site, and, second called Messages.js: this defines all the string literals that need to be localized, something like var ALERT_MSG = "Alert message in english".
2) Created different version of the Messages.js, one for each locale that we are supporting and localized the strings. The localized js files were named using messages.locale.js naming convention (for eg. messages.fr-FR.js).
3) Included the js files within the "ScriptManager" and provided the ResourceUICultures for the Messages.js file: this ensures that the correct localized file is embedded in the html output (if you are not using ASP.net you can build this basic functionality by doing some culture sniffing and including the appropriate js file).
4) Voila!
Your approach makes sense. Details:
I'd have the strings for each language in an object.
localized={"cat":"chat","dog":"chien"};
Then in code:
localized["cat"]
The quotations around of the keys and the array notation (rather than the more common object dot notation) are to avoid collisions with JavaScript reserved words.
There is a gettext library but I haven't used it.
Your approach sounds good enough.
If you have lots of strings and you are concerned about the bulkiness of the file you may want to consider a script that creates a single javascript file for each language by concatenating the code javascript and the locale javascript and then applying something like Minify.
You'll waste some CPU cycles on publishing but you'll save some round trips...
There's a library for localizing JavaScript applications: https://github.com/wikimedia/jquery.i18n
The strings are stored in JSON files, as pretty much everybody else suggests, but it has a few more features:
It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.
The only requirement is jQuery.

Categories