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.
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;
}
xmlhttp.send()
For XHTML generated client-side, use XSLT:
var processor = new XSLTProcessor();
processor.importStylesheet(your_xsl_template);
var xhtml = processor.transformToDocument(your_xml_data);
document.getElementById('my_placeholder').importNode(xhtml);
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:
document.getElementById('some_id').className.replace('old_class','new_class');
That’s it for today. What do you think?
Technorati Tags: Ajax, Web Development