Tuesday, March 17, 2009

Javascript: Good things to follow

List of some of the things that you might want to consider while working with JavaScript. Most of them are not hard to follow. I hope to expand on each one of them.


Keep JavaScript(s) in external file(s). Its easier to find where to debug and its much easier to put break pointers. Another reason to do so is the fact that browsers can cache files and hence faster page load.JavaScript that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document.

Avoid Global variables. Every JavaScript file included in the page runs in the same scope. If functions refer to variables in global scope, chances are that they overwrite values and interfere adversely. This can be avoided using name spacing.


Avoid hard coding values. This broadly is tendency to hard code values inside JavaScript function, for example


colorWarning = function(element) {element.style.color = 'red';}

If you decide to chose some other sytle for warning you would need to dig into the function. Instead of above try something like this


colorWarning = function(element) {element.className = 'styleWarning';}

Where styleWarning is a CSS class.


Avoid creating too much content with JavaScript. While page is being rendered and JavaScript tries to modify the content, you might get error "operation aborted error" (at least found on IE). You might consider using Ajax to load the data after initial page load. Another approach that you can take is to make any DOM modification post page load completion using window.onload


window.onload = function() {init(); doSomethingElse();}

Define variables with keyword "var". I have found script to act funny on IE when variables are not scoped with the keyword "var". Another problem of not declaring a variable with the keyword "var" is that whoever is reading your code would find it difficult to find where in the code the keyword got initialized.



0 comments:

Post a Comment