Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practices for writing HTML in 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?

like image 548
DLS Avatar asked Jan 22 '10 00:01

DLS


People also ask

What is the best practice for placing JavaScript in an HTML document?

</script> tag. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code.

How to use JavaScript with HTML?

Another good practice in using JavaScript with HTML is to place your JavaScript at the end of your HTML file if it is possible, between <script> tags, before the closing </body> tag, as you may notice from the above example.

What are the best practices for using variables in JavaScript?

JavaScript Best Practices Avoid Global Variables Always Declare Local Variables Declarations on Top Initialize Variables Never Declare Number, String, or Boolean Objects

When is JavaScript done on a website?

And, as Tom mentioned, JavaScript is done after the page is loaded; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [i.e. php]). Share Improve this answer Follow edited Oct 8 '09 at 6:45 answered Oct 7 '09 at 19:19

What is the use of hard JavaScript in HTML5?

It allows all the DOM elements to fully load before loading the JavaScript which addresses them, that means that a great part of page content, such as tables, images or text, to be loaded and performed first; so, in this point, the hard JavaScript can begin loading close to the end.


3 Answers

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

like image 54
Jaanus Avatar answered Oct 16 '22 23:10

Jaanus


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('&amp;').split('<').join('&lt;').split('"').join('&quot;');
}

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.)

like image 10
bobince Avatar answered Oct 17 '22 01:10

bobince


+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
like image 3
Mic Avatar answered Oct 16 '22 23:10

Mic