Ajax and the true separation of presentation, content and behavior

Articolo trovato qui: articolo originale

Contrary to what some may argue, you can use Ajax technologies in web applications and keep your code clean and separated from your presentation markup and content.

To kick off this column on Web Application development, I am going to address this issue with the 3 simple rules I used while working on the Form Builder.

Note: cross-browser considerations intentionally left out.

Rule #1: Use unobtrusive javascript

Don’t embed javascript inside your tags.

<a href="..." onclick="dostuff();"> do stuff </a>

This is just as bad as inline CSS or font tags.

Instead, do:

<a href="..." id="stuffDoer"> do stuff </a>

and have a separate javascript file, linked from the <head> of your page, with something like this :

document.addEventListener ('load', function() {
        document.getElementById('stuffDoer').onclick = doStuff;}, false);

See also these other recommendations.

Rule #2: Do not use javascript to generate markup

Or let me put it this way: build template driven applications. Use XMLHTTPRequest or XSLT to retrieve XHTML formatted strings, and insert them in your document.

The insertion point is identified by a placeholder, often an empty DIV element:

<div id="my_placeholder"></div>

For XHTML generated server side, use XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", someResourceURI, true);
xmlhttp.onreadystatechange= function() {
        if (xmlhttp.readyState==4) {
                document.getElementById('my_placeholder').innerHTML = xmlhttp.responseText;

For XHTML generated client-side, use XSLT:

var processor = new XSLTProcessor();
var xhtml = processor.transformToDocument(your_xml_data);

Note: The Sarissa wrapper provides a uniform syntax across browsers for all Ajax related coding.

Rule #3: Do not use javascript to style your content

Don’t do

document.getElementById('some_id').style.color = '#ff0000';

Instead do:

document.getElementById('some_id').className = 'some_class';

and set the color property in your CSS stylesheet

.some_class {
color:  #ff0000;

If you are trying to achieve a visual effect, you may want to consider class switching:



Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...