[JavaScript] Best Practices – Unobtrusive Scripting

I cannot say following best (or proven) practices are always good. But it helps you maintain code and develop complex code in a relatively simple and robust way.


1. Unobtrusive JavaScript

Unobtrusive JavaScript is a general approach to the use of JavaScript.

  • Separation of functionality (JavaScript) from structure (HTML) and presentation (CSS)
  • Progressive Enhancement
  • Graceful Degradation
  • Best Practices
  • Web Standards


2. Separation

  • Separate JavaScript from HTML

Traditionally, JavaScript was mixed with HTML, especially event handlers .

<input type="text" id="text1"
  onchange="validateText()" />

Unobtrusive JavaScript suggests to attach handlers programmatically.

window.onload = function () {
    = validateText;
function validateText() {


3. Graceful Degradation

  • Degrade gracefully – all content should be available even without all or any of the JavaScript running successfully

You want to use all the new functionalities of HTML5 and JavaScript. But what about old browsers that might not support the new features? You do not want the page just fails.

<canvas id="canvas1" width="400" height="300">
  <p>Your browser does not support HTML5 canvas.</p>


4. Progressive Enhancement

Progressive enhancement is a strategy for web design that allows everyone to access the basic content and functionality of a web page.

  • Separate the presentation in a separate CSS file
  • Keep HTML documents as simple as possible so that they work in even the most primitive browsers such as IE10 or before
  • Add features in a layered fashion so that the enhanced version of a page is provided for more advanced browsers


5. Web Standards

When you work with JavaScript, HTML, and CSS, try to stick on the web standard (W3C) and avoid using browser specifics.

Writing non-browser specific code is sometimes hard. The good approach is to use JavaScript Frameworks such as jQuery rather than raw JavaScript.

$(document).ready(function () {
  $('#click2').click(function() {
    alert("Button is clicked");

[Note] In production environment, use the framework library such as jQuery. Do not handle browser support issues by yourself.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s