While the design of a website is already separated from the content by using CSS (Cascading Style Sheets), the scripting features of a website can also be pulled out off the HTML file.

The technique to do this is called unobtrusive JavaScript and InfoQ.com has a nice writeup about it. Basically, instead of directly writing code into the event handlers of a tag, say onClick of an img you attach the code later in a JavaScript that is included at the bottom of a page. This means that you bascially traverse the DOM-Tree of the website and set the onClick property there.

While this is definitely a nice thing, there are caveats:
InfoQ.Com reader Gabriel Ka. points out that it will make the website harder to debug. Another reader, Luis Fernando Planella Gonzalez, points out that such a JavaScript at the bottom of a Website will make the website non-functional even some seconds after it has finished loading (at least in browsers with a slow JavaScript engine)

If you are interested in knowing more, read it on InfoQ or at a tutorial like the one of Michael Minella.

Are you interested in reading more from CodingClues?
Then subscribe to new postings via RSS or via E-Mail.

Viewing 2 Comments

    • ^
    • v

    With a good JS framework the page should not be harder to debug when adding the event handlers in a seperate script block. Actually, from my experience it is easier to debug, as the frameworks all make sure your event handler will recieve the event as first argument, no matter if you call the input parameter event (will work in IE) or for example evt (will not work in IE when used in onclick-attribute).
    Additionally, if you add your event handlers to single elements in an window.onload event handler (or even better, listen to dom:loaded), you avoid errors in event handler functions (imagine your onclick handler will change the innerHTML of another element that comes later in the DOM).
    The non-functional period is not a valid point in my opinion. The whole point of unobtrusive JavaScript is to markup your page in such a way, that it will work with JavaScript turned off. The JavaScript will then add additional features that increase the usability or the efficency.
    If your page doesn't "work" when the dom is completly loaded (and rendered), but the JavaScript isn't yet, then we are not talking about unobtrusive JavaScript. In that case you should hide elements that require JavaScript event handlers and show them via JavaScript after the event handlers were added.

    • ^
    • v

    There's an overview of jQuery on http://nettuts.com/javascript-...

    Apparently, jQuery does exactly what unotrusive JavaScript is promising: To keep code separate from presentation and content.

close Reblog this comment
blog comments powered by Disqus