11 Ways to use JavaScript efficiently

This article shows 11 ways to use Javascript efficiently

11 Ways to use JavaScript efficiently.

 

JavaScript is a powerful Scripting language, which has matured into a full-featured language that makes it possible to build powerful applications. It is the perfect complement to the disconnected nature of the Web interface, making it possible to perform many client-side operations without a trip to the Web Server, thereby providing User Interactivity and less overhead on the Web Server.

 

Below are 11 ways that I found to use JavaScript efficiently. These could be the use of inbuilt features as well as improving the way of writing Scripts.

 

i) Use Inbuilt Functions to perform Common Functions:

         

JavaScript has several built in functions to accomplish common functions. Use them to have a faster response and quick workarounds. For e.g. isNAN , is a function that can be used to check if a value is numeric or not.

 

The isNan Function returns true if the value is not numeric, and false if it is numeric.

 

e.g.     function chkDigits(obj)

{

   if (isNaN(document.getElementById(obj).value)==true)

   {

    alert("Please enter digits");

    document.getElementById(obj).focus();

    document.getElementById(obj).select();

    return false;

  }

}

 

You can call it like this,

 

<input id="Textbox1" value="ddd" onblur="return chkDigits(this);" >

 

ii) Use the DISPLAY attribute of the STYLE property instead of the VISIBILITY attribute of the STYLE property

 

When we use the “VISIBILITY” attribute of the Style Property to hide a control, it renders the control on the page and makes it invisible. But we can see that space being occupied on the web page. Instead, use the “DISPLAY” attribute. It does not render the control on the page. So it does not occupy the control's space on the page.

 

One more added advantage of using the “DISPLAY” attribute is the page size being decreased. Although, the decrease is only in terms of few Kilobytes’ , they certainly take up some client resources.

 

iii) Use Caching in JavaScript. It Improves Performance.

 

Along with caching the objects, you can also enhance a script's performance by caching the entire script by including it in a .js file. This way, the browser loads the script only once and recalls it from the cache for the subsequent requests:

 

<script src="reqscripts.js"></script>

 

You can use this method when your scripts are large or being used in multiple pages.

 

 


iv) Make Loops run Faster:

 

Loops are a fundamental part of many scripts, and in general they cause no problems at all. However, it is possible to make them run faster, by using an optimized conditional.

 

JavaScript often repeatedly accesses a certain object, for instance:

 

<script language="JavaScript">

          for (i=0;i<document.images.length;i++)

           document.images[i].src="temp.gif"

</script>

 

In the above example, the object document.images is accessed multiple times, forcing the browser to dynamically look it up twice during each loop (once to see if i<document.images.length, and once to access and change the image's src value at the current loop index). So if you've got ten images on the page, the script makes 20 calls to the Images object. Excessive calls like this not only slow the browser, they also take up memory, thereby slowing your system.

The way to fix this is to store a repeatedly accessed object inside a user defined variable, and use that variable instead of the actual object. Like this:

<script language="JavaScript">

          var theimages=document.images

          for (i=0;i<theimages.length;i++)

             theimages[i].src="temp.gif"

</script>

 

In the above script, document.images[] is referenced only half as many times as before. It goes to the array the second time, instead of the object.

 

 

v) Referencing elements

The DOM provides many ways to reference elements. We use getElementById to reference the element. You need to use getElementsByTagName to ensure you reference the correct element type.

Say for example that you want to reference all DIV elements on the page. You can use getElementsByTagName('*') or get the form collection, but this will reference far too many elements, and will make your loops much slower as they check to see if it is the correct element. This is a bad way to do it, and should only be used if you need to reference the DIV’s in the correct order:

var divs = document.getElementsByTagName('*');

//or var divs = document.form1.elements;

 

for( var i = 0; I < divs.length; i++ )

  {

      ..//check for Element Type= div

  }

 

Instead use,

 

  var divs = document.getElementsByTagName(‘div);

  for( var i = 0;i < divs.length ; i++ )

  {

    ...

  }


vi) Matching Strings

If you need to search a within one string to see if it contains another string, there are many ways to do it.  “IndexOf”, Search, Match are few ways to be mentioned.

The first , 'IndexOf' finds the position of the substring within the string. The second is to use 'match' or an equivalent method to find if a regular expression pattern can be found in the string.

All string matching techniques are very fast, but they should be used carefully to avoid making them wasteful. In general, for basic and simple string matches, stringObject.indexOf is faster than stringObject.match.

You should avoid matching against very long strings unless you absolutely have to. If you are certain that the match will only occur in a specific portion of the string, take a substring, and compare against that, instead of the entire string.

Using regular expressions with large numbers of wildcards will make string matching noticably slower.

Vii) Keep your Scripts DRY (Don’t repeat yourself) .Create once, use repeatedly

If you use the same regular expression or string repeatedly, you should create it once and store it in a variable that you can use for matching. This allows the browser to be faster and more efficient.

In the example below, the two regular expressions are treated separately, and will cause the browser to waste resources creating two separate expressions that contain the same value:

if( a == 1 && obj1.value..match(/[aeiou]/) ) {

  //this creates the first copy

} else if( a == 1 && obj2.value..match(/[aeiou]/) ) {

 {

  //this creates a second copy

}

 

This equivalent code would work identically, but would be more efficient, as the browser only needs to create one copy of the expression:

 

var ChkExpr = /[aeioui]/

if( a == 1 && obj1.value..match (ChkExpr) ) {

  //this uses the existing variable

} else if( a == 2 && obj2.value..match (ChkExpr) ) {

  //this also uses the existing variable

}

 

Viii) Avoid running unnecessary code

If your script is only supposed to run if certain conditions are satisfied, check for those conditions as early as possible, and stop the script immediately if the conditions are not satisfied. If your script is inside a function, you can use return to stop the function.

There is also a similar way to break out of 'for' or 'while' loops, and conveniently, it is called 'break'. Say, for example, that you need to scan through all <div> tags on the page, and their style attribute references a particular css file, replace it with another file. Once you have done that in a for loop, there is no need to continue checking the other <div> tags. You could use 'return' to stop processing the function. You could waste a little bit of memory by storing an extra variable that says if you have found the correct tag, and add that into your loop conditional. Depending on the circumstances, that may not be so simple, and it is more easy to just break out of the loop.

ix) Cut the Conditions Short. Take a short circuit

The short circuit operator (&&) helps you to optimise your conditional statements, allowing an expensive operation to be performed only if a less expensive condition check is successful. It ensures that the second condition is only evaluated if the first one is satisfied.

This is most often used to avoid errors by checking for properties before trying to check for their methods:

If ((obj.Type == “checkbox”) && ( obj.checked ) )

 

The short circuit operator also makes it possible to increase the efficiency of your script.

The || operator performs in a similar way, only evaluating the second condition if the first one is not satisfied. If you have two conditions, where only one of them needs to be satisfied for you to continue, you can put the least expensive one first, so that the second one will only be avaluated if the first one fails.

if( eName.indexOf('unsupported') || eSource.match(/\bnav\.excluded?\s*==/) )

 

 

x)  Assign multiple styles

It is common to want to assign several styles to an element. Normally this is done with this wasteful syntax:

obj.style.position = 'absolute';

obj.style.top = '0px';

obj.style.left = '0px';

... etc ...

This can often be reduced to a single assignment, saving time, reducing the number of assignments the browser needs to perform, and reducing it to a single reflow:

obj.setAttribute('style','position:absolute;top:0px;left:0px;... etc ...');

 

 

xi)  Put all styling in a stylesheet file

If you have lot of style elements/tags in your html, the file size increases. Every time a page loads the styling elements and tags also get loaded, and is also returned to and from the server. But if you use all these elements in a stylesheet, it will get cached by the browser and thereby only return from the server once, and also loaded by the browser once. This can be a great improvement if you have a lot on in-code styling.

By [)ia6l0 iii   Popularity  (1957 Views)