Thursday, March 20, 2014

What is 'Unobtrusive JavaScript'?

This is the first interesting term i came across when i started reading Jquery In Action.
  • Unobtrusive JavaScript is about 'separating the behavior (i.e JavaScript) from the Web Page Structure/Markup (i.e HTML).
  • This is very much similar to separating the 'Style' (i.e CSS) from the HTML.
  • Following this approach achieves 'separation' of responsibilites- i.e All style related information is captured in separate CSS files, All Java Script behavior (Handling of events etc etc) is captured in separate JS files and the web page will just contain the HTML markup.
So the next question is how to write Unobtrusive JavaScript (or how not to write obtrusive JavaScript)?
  • Don't put any script blocks within the body of the page.
  • Don't write in-line JavaScript. Below line is an example of obtrusive JavaScript:
    <input type="radio" name="view_radio" id="global" onclick="selectList(this.value)">
    

    The JavaScript function that is invoked when a radio button is selected is defined as an attribute of a HTML element - i.e Behavior and markup are combined.Unobtrusive solution is to separate the behavior from markup (i.e remove the onclick attribute in HTML) and register the necessary event handlers programmatically.
$('[name="view_radio"]:radio').click(function() {  
     var checked = $('[name="view_radio"]:radio:checked').val();
     if(checked == "X") {       
   // do X processing         
     } else {
  // do else processing
}
}

Improved maintainability and solving browser incompatibilities are the main advantages of following this approach. So next time you see an inline handler coded directly in HTML , think about how to remove it and register for the events directly in JavaScript.

No comments:

Post a Comment