Categories:

3 performance tips for JavaScript

As our JavaScript applications get larger and ever more sophisticated, the need for efficient scripting becomes increasingly important and hard to bypass. Back in the days when all that JavaScript could do was change your document's background color, or validate a simple form, abuse in terms of efficiency in our codes was common, with the browser not having a problem with it at all. Now, especially with the language's marriage with DHTML, in turn, the ability to create almost full blown applications, efficiency is no longer something we can sweep under the rug, and forget about.

In this tutorial, I'll show you a trio of important and generic tips for improving performance  in your JavaScript codes. Pop in your favorite tune, and let's sweat JavaScript to the old East!

Tip 1: Cache your objects!

One of the best kept secrets to boosting script performance is to cache your objects. Often times, your script will repeatedly access a certain object, as in the following demonstration:

<script type="text/javascript">
for (var i=0;i<document.images.length;i++)
	document.images[i].src="blank.gif"
</script>

In the above, the object "document.images" is what's accessed multiple times. The code to realizing it is inefficient, since the browser must dynamically look up "document.images" twice during each loop (once to see if i<document.images, and the other, to access and change the image's src). If you have 10 images on the page, for example, that's 20 calls to the Images object right there. Excessive calls to JavaScript objects can wear down the browser, not to mention your computer's memory.

The term "cache your object" means storing a repeatedly access object inside a user defined variable, and using that variable instead in subsequent references to the object. The performance improvement can be significant. Here's a modified version of the initial script using object caching:

<script type="text/javascript">
var theimages=document.images
for (var i=0;i<theimages.length;i++)
	theimages[i].src="blank.gif"
</script>

Not only is the number of times document.images[] is referenced cut in half with the above, but for each time it is referenced, the browser doesn't have to go through document.images first, but goes straight to its containing array.

Remember to use object caching when calling highly nested DHTML objects, like document.all.myobject, or document.layers.firstlayer etc.

Tip 2: Cache your scripts!

You've "cashed in" your objects...another way to enhance script performance is the cache the entire script, by including it in a .js file. The technique causes the browser to load the script in question only once, and recall it from cache should the page be reloaded or revisited.

<script type="text/javascript" src="imagescript.js"></script>

Use script caching when a script is extremely large, or embedded across multiple pages.