Search This Blog

Sunday, January 13, 2008

JavaScript Best Practices

Use Object Oriented JavaScript
• Provides better reusability of the code
• Enables your objects to be better organized
• Allow for dynamic loading of objects

Use Object Hierarchies to Organize JavaScript Objects to Avoid Name Collision
• In JavaScript there is the potential for object names to collide. In Java language, package names are used to prevent naming collisions
• JavaScript does not provide package names like Java however you can when writing components use objects and object hierarchies to organize related objects and prevent naming collision

Use the prototype property
• Use it to define shared behavior and to extend objects
• The prototype property is a language feature of JavaScript. The property is available on all objects

Write reusable JavaScript
• JavaScript should not be tied to a specific component unless absolutely necessary
• Consider not hard coding data in your functions that can be parameterized

Object Literals
• Object literals are objects defined using braces ({}) that contain a set of comma separated key value pairs much like a map in Java
• Example
{key1: "stringValue", key2: 2, key3: ['blue','green','yellow']}
• Object literals are very handy in that they can be used as arguments to a function
• Object literals should not be confused with JSON which has similar syntax

Load JavaScript On Demand
• If you have a large library or set of libraries you don't need to load everything when a page is loaded
• JavaScript may be loaded dynamically at runtime using a library such as JSAN or done manually by using AJAX to load JavaScript code and calling eval() on the JavaScript

Separation of content, CSS, and JavaScript
• A rich web application user interface is made up of
content (HTML/XHTML), styles (CSS), JavaScript
• Separating the CSS styles from the JavaScript is a practice which will make your code more manageable, easier to read, and easier to customize
• Place CSS and JavaScript code in separate files
• Optimize the bandwidth usage by having CSS and JavaScript file loaded only once

Reduce the size of JavaScript file
• Remove the white spaces and shortening the names of variables and functions in a file
• While in development mode keep your scripts readable so that they may be debugged easier
• Consider compressing your JavaScript resources when you deploy your application
• If you use a 3rd party JavaScript library use the compressed version if one is provided.
Example compression tool: ShrinkSafe

To read the actual article, you could download the pdf file from the following link.

No comments: