Make Sure Your Functions Are Loaded
First, you should make sure your functions are loaded, which is easy to do. If you use a function that isn't loaded, your code will malfunction. What's more, it's almost certain to malfunction in a manner that leaves no doubt in the reader's mind that something went wrong-and that it's your fault. If there are JavaScript expressions in the body of your page and those expressions call other JavaScript functions that you wrote, place those JavaScript functions in a <SCRIPT> element within the <HEAD> element. The< HEAD> element is loaded before the <BODY> element; you can depend on the function being there. This approach prevents a user from impatiently clicking on a partially loaded page and invoking a JavaScript function that hasn't been downloaded from the server yet.Validate Input
If you're getting input from the reader, make sure you check it before blindly using it, especially if it's supposed to be a number. Use the parseInt() and parseFloat() functions. If it's supposed to be an integer, check it like this:
if (Math.ceil(x) == x)
{
// it's an integer
}
else
{
// oops...
}
The Math object's ceil() method returns the next higher integer for a floating-point value; for an integer value, it will return the same value. The floor() method will also work. Finally, if the number is supposed to be within a certain range of values, make sure that it's within the specifications. For example, if it's supposed to be a value from 1 to 10, put something like this in your code:
if (x < 1 || 1Ø < x)
{
alert("" + x + "is not between 1 and 1Ø");
return;
}
But Surely No One Would Do That!
Sometimes users will input data that they're not supposed to. Some users will be confused about what they're supposed to enter; they won't understand what they're supposed to do. Other users will deliberately try to make your page crash just for fun. Assume that when you ask for a number, someone is going to enter anything except a number. "But you're not supposed to do that" is not a valid defense for letting your code malfunction just because you asked for a number but someone entered a phone number or the word "no."Not All Platforms Are Created Equal, Part 2
There are some differences between the implementations of Netscape Navigator for the various supported platforms. You can't expect everyone to use the same platform that you use, and you should write your code to defend against problems tied to specific platforms:- Macintosh and Windows browsers can't return NaN (Not a Number) when you call parseInt() or parseFloat() and the argument is not a number. They return 0 instead.
- random() only works on UNIX platforms.
- Xwindow platforms have difficulty drawing new browser windows. Even if you specify the parts of the window you want, you're going to get a bare window.
- When you open a new document, call open() twice. Windows and Macintosh browsers won't open the document unless you call open() twice.
No comments:
Post a Comment