Good Javascript Practices

I decided to share some of the best practices of Javascript which I have learned from various blogs and books over the years. Although, I used Javascript back in 2003, I didn’t learn Javascript properly and just happened to use it for some fun webpages. However, as I revisited Javascript from 2007 onwards, I have started to use Javascript as an OO language and try to follow the best practices.

Below are a list of 7 such Best Practices of Javascript:

#1. Making Scripts External

Making Javascripts External keeps it separate from the HTML file and as such is easier to maintain. Also one can set an expiry date for the external js file (In Apache, expiry can be set using mod_expire), and thus the page loading would be much faster.


#2. Placing Scripts at the bottom

Javascript code should be placed at the bottom of the page right before the ending </body> tag. Script blocks parallel downloads, hence keeping them at the top of the page would block the downloading of the page until the Javascript has been completely downloaded. So, its best to put Javascript at the bottom. Read more on Yahoo Developer Network

So, typically scripts code block should be like below:


< /body>

#3. Avoiding too many Global Variables

Instead of declaring multiple variables like below:

var name = "Alexander";
var gender = "male";
var phone  = "416-999-9999";

function updatePerson(n,g,p) {
name = n;
gender=g;
phone=p;
}

Its better to re-organize variable and declare it like below in JSON Format:

var Person = { 
 name: "Alexander", 
 gender: "male", 
 phone: "416-999-9999"
 update: function(info) {
 // info is a object containing name, gender, phone. 
 // process accordingly
 }
};

#4. Using Shortcuts

Instead of declaring arrays like:

var nameList = new Array();
nameList[0] = "Alif"; 
nameList[1] = "Alexander";
nameList[2] = "Totem";

Its better to use:

var nameList = ["Alif", "Alexander","Totem"];

Using ternary operator instead of if-else, depending on circumstances. (Some developers I have worked with on projects, have asked me not to use ternary operator as it complicates the readability of coding, so this point is debatable, and hence its upto individuals to decide).

Instead of using:

var x;
if(cond == true) {
x = "A"; 
} else {
x = "C";
}

Use:

var x = cond ? "A" : "C";

#5. Unobtrusive Scripting

Instead of using inline Javascript, the Javascript code should be separated out from the HTML codes. From the Javascript, a specific tag/node should be grabbed to attach an event or do something else. For example, instead of using:

Show Users

Grab the element/node from the Javascript separately and attach the function with it:

document.getElementById("showUsers").onclick = function() {
showUsersList();
return false; // or event.preventDefault() for non-IE;
};

#6. Progressive Enhancement

Progressive Enhancement technique starts with offering a minimal level of user experience that all browsers will be able to display. Then, on top that, more advanced functionality are built to enrich user experience.

For example, when the following code block is used:

Show Users

It is assumed that the visitor/user has a Javascript enabled Browser.

But, what if the user doesn’t have Javascript enabled? and even worse, what if the user doesn’t know or do not have permission to “enable/allow” javascript?. For that case, the above script will not work, and non-JS users will not be able to see the functionality of “Show Users”.
So, the following technique should be used:

Show Users

From the Javascript, the element should be grabbed and onclick event should be attached as described on #5. And a functionality of ‘url.php?s=all’ should be added to the page to ensure non-JS users gets to see the same feature at a degraded user experience.

#7. Minify Javascript

Javascript should be minified whenever applicable (minify means to strip out comments and white spaces, carriage returns etc.). There are some great tools online to minify a Javascript.

My favorite one is YUI Compressor, an online version is here. Minifying scripts reduces the file size significantly (depending on your code). As a rough example, jQuery 1.4 actual is 155kb, whilst minified version is ~74kb.

Thats about it !.

Please note that I am still learning as time progresses, as a result, if you find any of the above practices as ‘not the best practice of JS’, then notify me.

For more reading, please visit the following resources:

Opera Developers | Javascript Best Practices

ezMark: jQuery Checkbox & Radiobutton Plugin

ezMark is a jQuery Plugin that allows you to stylize Radio button and Checkbox easily. Its very small (minified version is ~1.5kb) compared to other similar scripts. It has been tested and works on all major browsers (IE 6/7/8, Firefox, Safari, Chrome) and it gracefully degrades.

It has the following Method:

$('selector').ezMark( [options] ); 

Basic Usage:

Include the CSS file:


Then include the jquery.js file and the plugin file:



Write the HTML tags normally, as you would type them


Now, call the following method in your JS (to apply on all checkbox & radiobutton across the page):

$('input').ezMark();

Likewise, you can also use custom selectors for checkbox or radiobuttons:

// to apply only to checkbox use:
$('input[type="checkbox"]').ezMark();

// for only radio buttons:
$('input[type="radio"]').ezMark();

Parameters:

options parameter accepts the following JSON properties:

Parameter’s (JSON) Properties: Explanation/Details of the Property
checkboxCls The Checkbox Class as per declaration on CSS.
checkedCls The Checkbox Class on Checked State
radioCls The Radio button’s Class as per CSS
selectedCls The Radio Button’s Class on selected State

To customize the default checkbox/radiobutton image, change the background image (checkbox-black.png/radio-black.png) and CSS (ez-checkbox/ez-radio) and (ez-checked/ez-selected) accordingly.

Customized Usage:

After you have customized/created your own css class. Simply call the ezmark method like below:

// to apply only to checkbox use:
$('input[type="checkbox"]').ezMark({
 checkboxCls: 'your-default-checkbox-class-name' ,
 checkedCls: 'your-checkbox-class-in-checked-state'
});

// for only radio buttons:
$('input[type="checkbox"]').ezMark({
 radioCls: 'your-default-radiobutton-class-name' ,
 selectedCls: 'your-radiobutton-class-in-selected-state'
});

View Demo

Download from Github

Download from jQuery Server