1. Computing & Technology

New JavaScript Commands

From , former About.com Guide

Every so often a new version of a web browser introduces a new version of JavaScript that contains a few additional commands. In some cases these new commands are a part of the developing JavaScript standard and are just ones that other browsers haven't implemented yet. Other times the commands are proprietary ones that the browser creators are hoping will prove to be useful enough to add it into the standards.

Since all browsers do not support the new commands you have to consider things very carefully before you use them.

To start with it is not necessary to ensure that your script will work in all browsers. It can't since there are browsers that do not support JavaScript at all and so none of your JavaScript will work in those browsers.

Also there are many old browsers that only support early versions of JavaScript. Very few people still use those browsers and they should be used to most JavaScript not working by now and so supporting the really old browsers isn't really necessary either.

You do need to support all the browsers that are still in common use though. This does not necessarily mean that your JavaScript has to work for all these visitors, just that the page works without giving errors. Since a properly designed web page works without JavaScript you can always use feature sensing on the commands you want to use and not run the JavaScript at all where those commands are not available. If you do that then those of your visitors whose browsers don't support those commands will see the page the same way those without JavaScript see it.

Another alternative is to supply your own version of the command for those browsers that do not have it built in. Commands such as getElementsByClassName() and forEach() can readily be used in all popular browsers whether the browser actually supports the command or not simply by using feature sensing to test if the command exists and if it doesn't then add your own code to perform the functionality. That way your code will work when you use those commands whether the browser recognises them or not.

Adding the code ourselves all the time without using feature sensing at al will also work but has one disadvantage in that the built in version of the command will usually run faster than the code you write to do it yourself and so allowing the browser to use the built in version where it exists will make your code more efficient in those browsers while the code you supply will allow those browsers that do not have the command built in to still run your code even though it will run more slowly in those browsers.

©2012 About.com. All rights reserved.

A part of The New York Times Company.