Writing Unobtrusive JavaScript comes with some other considerations.
- First and foremost moving the 'behavior' (i.e JavaScript code) outside the markup results in increased lines of code. Here Jquery comes to our aid in accomplishing more with less lines of code. And it inherently takes care of the browser incompatibilities too. So we can very well say that we write Unobtrusive JavaScript mostly in 'Jquery' style/notaion. (You might have noticed the Jquery style in the example in previous link)
- Unobtrusive JavaScript talks about registering necessary event handler programmatically. Where we can register these? window.onload handler is a traditional choice for this.
- Disadvantage of putting this code in window.onload handler is - for this code to get executed we have to wait until all the external resources (images, videos etc etc present in HTML) are fully loaded. This results in poor user experience as the 'rich behavior' defined in scripts is not seen until browser finishes loading and displaying every image and resource.
- This disadvantage questions the approach oj Unobtrusive Javascript itself.
Jquery's solution to this problem is to use document ready handler.Here we instruct the browser to wait until only DOM is loaded before executing the code. (No waiting for loading of external images etc). And Jquery handles this in a consistent manner across different browsers.
<input type="radio" name="view_radio" id="global" onclick="selectList(this.value)">
$(document).ready(function() { $('[name="view_radio"]:radio').click(function() { var checked = $('[name="view_radio"]:radio:checked').val(); if(checked == "X") { // do X processing } else { // do else processing } } });
No comments:
Post a Comment