Site navigation below

In this section

Place your text ad here.

World class Undelete and renowned raid recovery services

Web Scripts and PHP Scripts

WestNIC provides reliable web hosting services

SGD Networks offers Web Hosting, Web Hosting Hyderabad

Javascript is one of the cornerstones of "cool" interactive Web design and can provide useful client-side verification, navigational enhancement and feedback functions. As with so many things though, a little knowledge can be a dangerous thing. Before you abandon your conscience to the next cut-and-paste repository, understand the golden rules of Javascript.

Three essential questions

There are three essential questions to ask before using client side Javascript on the Web:

  1. Is Javascript likely to be available and enabled in all the browsers that will load the page?
  2. Are all the objects, methods and properties that the script uses supported by all the browsers likely to load the page?
  3. Are there workable or tolerable fallback options in both cases above?

Still confident your script will stand up on the World Wide Web? There are good reasons to suggest you shouldn't be. Read on to find out why, and what you can do about it.

Question 1: Javascript support?

The answer to question one is certainly "No". No matter how technologically advanced you imagine your target audience to be, and whatever your Web server logs tell you, if your Javascript page is on the World Wide Web it will be loaded by non-supporting user agents and in these cases your code will not execute.

Spiders and crawlers

Amongst the most important non-supporting user agents are the spidering applications used by Internet search engines to index Web sites. These crawler programs do not have Javascript interpreters and will not follow navigational routes that require Javascript, nor index text that is generated dynamically by Javascript. If you want your Web site to be listed with the top search engines, don't make it a black hole for spiders.

Alternative browser devices

Other non-supporting user agents include the relatively simple browser versions used in public kiosks, games consoles and hand-held devices such as mobile phones and PDAs, and those that interpret or read Web pages for visually impaired users. You may not consider the people who happen to use these applications your primary audience, but they could be if you spent a little extra time thinking through the noscript alternative.

Security blocks

Some people who access the Internet at work find they have heavy handed network administrators who have disabled their Web browsers' script support or configured security software to strip out the Javascript content of Web pages.

If a browser's script support is disabled, authors might reasonably rely upon noscript elements to back-up their code. However, the logic with which security software extracts script blocks and event handlers is practically impossible to predict in every circumstance and leaves some uncertainty about what functions, objects and variables might be available at run time.

Be pessimistic about what parts of your script might have got through such a security blockade and consider the impact, but don't over-compensate; this uncertainty is ultimately unpredictable.

User preferences

However safe you believe Javascript to be, certain users lack such faith in the good intent of script authors, or perhaps the ability of their browser to block script attacks on their systems. The profusion of pop-up windows on the Web can be enough to persuade users to disable script support in their browser, and in these circumstances your code will not run.

The user's loss, perhaps, but if your page doesn't "work" or look right, people are unlikely to return to your site and their disappointment becomes your loss too.

Question 2: Which Javascript features?

The fundamental uncertainties of script authoring for the World Wide Web are compounded by variations in browser support for specific document objects, properties and language methods. A broad understanding of the script language and the history of its implementation will help considerably, but ultimately it is not possible to guarantee that all required features will be available in all browsing situations.

Browser "sniffing" doesn't work

Many Javascript tutorials, code repositories and references will provide sample code that attempts to detect the type and version of the browser that loads a given script in order to present specially tailored code for that browser. The nature and history of the World Wide Web means that this browser "sniffing" can only create less robust, less manageable and less accessible Web sites.

Spoof user agents

Previous ill-conceived attempts only to serve Web content to certain "advanced" user agents has forced Web browser vendors, including Microsoft and Opera Software, to make their applications report false user agent names and versions, and thereby "spoof" such checks. Hence, a user agent that announces itself as Internet Explorer 5.0, may actually be the Opera browser configured to access unnecessarily restrictive Web sites.

The myth of the "big two"

The nature of many browser sniffing scripts also serves a self-selecting theory that the only browsers worth scripting for are Netscape Navigator and Microsoft Internet Explorer. Other browsers are often excluded from Web sites by short-sighted script authors who compare user agent strings for one or other of these major versions. Even worse, some script logic assumes that if it's not one of the big two it must be the other, exposing inappropriate code regardless.

Sub-version variations

Historically, major version browser releases include bugs that require sub-version bug fix releases. Many ISPs also commission and distribute their own browser versions to their subscribers. In all cases these variations may include changes to the browser's Javascript implementation that limit or alter the features that are assumed to present in the major release. However hard one might try, it would be an impossible task to identify, test and track all the browser variants and work to their individual script implementations.

Question 3: A tolerable fall-back?

The notion of "graceful degradation" is that Javascript code may be designed from the bottom up to present a reasonable rendition of the page content whatever the end user's browsing environment. This is the ideal. However, complex Javascript applications may have no meaningful equivalent in static markup, tempting authors to the belief that users should use only those browsers that are known to support their code (the "Best viewed in browser X" syndrome).

Is this tolerable from a user's point of view? Would you install or choose to run a different browser just to view a single Web page? Probably not.

The point of no return

Is there workable fallback? If the answer is "no", one should certainly reconsider. In this case Javascript is part of the problem, not the solution, and you are actively contributing to a less useful Internet. If the successful execution of your script is essential for site navigation or function, users will meet a dead end or a flurry of error messages, to which the most likely response is to hit the Back button and never return.

The golden rules

Let's not abandon Javascript altogether, though. What can be done to ensure graceful degradation in most circumstances? The golden rules are:

  1. To understand the consequences of noscript and design applications to address this possibility in all cases. If Javascript is only used to enhance the user experience, it may be acceptable to do nothing.
  2. Adopt a "defensive" coding strategy. Use object, method and property checking, rather than browser "sniffing", to work around most eventualities (see below).
  3. Test scripts in as many browsers as you can get hold of to ensure that, in principle, your error handling is robust and debugged in a known range of browser environments. You may not identify all possible problems, but at least you will have made an honourable effort.
  4. Ensure that client side scripting is not the final fallback for your Web application and ensure that server side solutions are available to address whatever shortcomings may arise with your client side script.

Defensive coding

If the consequences of noscript are accepted, it is possible to develop advanced Javascript applications that minimise the uncertainties posed by question two. It is impossible to be sure which minor version of a given Web browser might load your code, but Javascript does give you relatively simple ways to check what objects, methods and properties are available in a particular browser environment. What's more if you build this type of error checking into your scripts, your code may run error-free on browsers you've never even heard of.

Object checking

One typical example of object checking is to ensure that the Image object and properties exist before assigning values. Use an if condition to contain the relevant sections of code:

if(document.images){
  var buttonOff = new Image(30,10);
  buttonOff.src = '/images/buttOff.gif';
  var buttonOn = new Image(30,10);
  buttonOn.src = '/images/buttOn.gif';
}
else{
  // Image object references, methods
  // and properties are not supported, so
  // don't attempt to use them
}
      

Method checking

The Window and Document objects are core Javascript features and can be expected in all circumstances, but which methods are supported? Again, use an if clause to contain the relevant methods:

var fbtext = "Feedback text";

var fbwin;

if((window.focus)&&
    (document.open)&&
    (document.write)&&
    (document.close)){

  // All necessary methods exist
  fbwin = window.open('',
                      'Feedback',
                      'width=410,
                       height=200,
                       menubar=no,
                       status=no,
                       toolbar=no,
                       resizable=no');
  fbwin.document.open();
  fbwin.document.write(fbtext);
  fbwin.document.close();
  fbwin.focus();
}
else{
  // Some critical methods don't exist,
  // use a standard alert instead
  alert(fbtext);
}
      

Property checking

Finally, the initial properties of certain objects may not be as you would expect in all browsing conditions. In most cases you should first check that the relevant object exists. This example from DOM1 visibility menus illustrates a workaround for the .style.visibility property in Internet Explorer 5:

// This is the new 'live' menu, make it visible
LiveMenu = document.getElementById(MenuID);

// LiveMenu.style.visibility is
// initially empty in IE5 until
// it is assigned by these
// functions, so must check that
// it's not null before proceeding...
if((LiveMenu.style)&&(LiveMenu.style.visibility!=null)){
  LiveMenu.style.visibility = 'visible';
}
      

Browser checking and debugging

Ultimately, nothing beats actually testing scripts in a range of browsers, and the broader the range of browsers that are used to do so the better. Acquire and install however many browsers you can on whatever platforms you have available to make sure your code is watertight and executes error free.

Debugging Javascript can be lengthy process of trial and error as one gradually isolates the problematic code or conditions. There are practically no short cuts in this process, but having a structured view of the dependencies of key functions on specific language or object model features will be a significant help.

Frequently Asked Questions

Article feedback

Your comments on this article will be appreciated, please use the form below to submit your views. If you would like a reply or article update notification, include your email address.

Information: Your email address will not be mis-used. If you include your address you may be sent a personal reply, you will not be added to any mailing list unless you request update notification. Read the site privacy statement for details.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log