Javascript Optimization Techniques

More and more sites have begun using javascript to implement a wide array of features like DHTML, AJAX and various type of validations and processing

Reduce the size of javascript source code

The first and the most obvious suggestion for this would be to avoid whitespaces as much as possible.

Next, the prototype techniques can be used to reduce the size of you javascript code considerably. document.getElementById is one of the most extensively used function in javascript and when used a lot of times it increases the overall size of the javascript code considerably.
One way is to use a smaller name for this general purpose function like $() just as prototype does.

function $(element) {
  return document.getElementById(element);
}

//or the prototype way

function $(element) {
  if (Object.isString(element))
    element = document.getElementById(element);
  return element;
}

//or

function $(id) {
  if(typeof id == "string")
    return(document.getElementById(id));
  return id;
}

now if there are 50 occurences of document.getElementById in your javascript file then you get a saving of 1100 characters of say nearly 1 KB!!

Similarly for document.getElementsByTagName

function $$(tag) {
  return document.getElementsByTagName(tag);
}

To Get the values of input boxes

function $V(tag) {
  return document.getElementById(element).value;
}

Fast and Space saving!!

Similary the document.writeln can also be named to a smaller name.

Improving Execution Speed

And for this the first suggestion would be to use better logic for the javascript processing, dhtml effects etc.

Next, un-needed variables should be removed from memory by setting them to null like :

variable = null;

So go ahead to save space and bandwidth.

Popularity: 1% [?]

Leave a Reply