Wednesday, February 25, 2009

Unobtrusive javascript

What?
Separate out javascript from HTML document, while retaining intended look and interaction. Traditionally javascript are written inline with the HTML markup, for example

<button onclick="alert('I am inline')">click me</button>

Results in a button like like this

Why?

Demand for cross browser compatibility. Remember different browsers have different javascript engine or might not have javascript engine at all. Further a method available in a particular browser (or browser version) might not be available in another. For these reasonstThink of javascript as an option but not a requirement.

Who?
The term was coined by Stuart Langridge in 2002

How?
Expected behavior from DOM element can be added after HTML page is completely loaded inside the browser. One way of achieving it is by using window.onload method.
The code for expected behaviour from the DOM element can be added in the head block of the HTML or towards the end of the HTML document before the body tag closes. The method I chose to stick to is to write javascript in a separate file.
In my opinion this approach may lead to a bit of extra effort but this helps you to keep concerned code in one place. If something goes wrong you know where to look for.

And more

Apart from separating javascript from HTML structure, it is ideal to separate out CSS as well. I prefer to write CSS in a separate CSS files rather than having them in head block.

Find more

A link leads to another, you can find more information and more information on more information at
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

0 comments:

Post a Comment