Pages

Monday, December 12, 2011

Separate script tags can help insulate good JavaScript code from bad

As developers, sometimes we like to think of ourselves as perfect. However, whether you blame other developers, clients, etc., the fact remains that mistakes happen. Unfortunately, often one bad apple in a script ruins the whole batch. For example, consider the following code:

<script language="javaScript" type="text/javascript">
   //Lots of code...
   var 0t = "la";
   //Lots of other code...

   function Myfunction() {
    alert(document.form1.txtbox.value);}
</script>

Anything that tries to call the function Myfunction will fail. In fact, when debugging a case such as this, it's very easy to assume that there's something wrong with Myfunction. But that isn't necessarily the case. We simply added a bad variable declaration above it. Since variables can't begin with numbers, JavaScript stops working at the first line in the script.

If the part of the code that had the error turned out not to be that critical, it's really a shame that it messed up your wonderful function. But you can insulate against this problem by simply creating different script blocks, so that each piece of functionality fails or succeeds separately, like this:

<script language="javaScript" type="text/javascript">
   //Lots of code...
   var 0t = "la";
   //Lots of other code...
</script>
<script language="javaScript" type="text/javascript">

   function Myfunction() {
    alert(document.form1.txtbox.value);}
</script>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.