Using VBScript and JScript on a Web Page

 

Microsoft Corporation

September 1998

Summary: Discusses the differences between VBScript and JScript and when to use each. (11 printed pages) Also covers:

  • Specifying VBScript and JScript in Microsoft Visual InterDev
  • Inline server scripts and the <Script>element
  • Script execution order

You're writing a Web page and you decide that you need to write some script. Fortunately, you can choose from several scripting languages. Unfortunately, there are several languages to choose from, which puts the decision on you. What should you do?

Or you inherit a page with existing script written in a scripting language that you don't normally use. Do you have to learn that script just to add a few functions?

In this article, I'll address both of these issues. First, I'll give you some guidelines for working with the two scripting languages provided by Microsoft:

  • Microsoft® Visual Basic®, Scripting Edition (VBScript).
  • JScript®, which is Microsoft's version of ECMAScript, the standard definition for a group of scripting languages that includes JScript and JavaScript.

There are other Web scripting languages available as well, such as Perl and Rexx. However, here I'll concentrate on the two languages for which Microsoft ships an ActiveX® Scripting Language engine in Internet Explorer and in Internet Information Server (IIS).

I'll then discuss the times when you might want or need to use both languages on the same page (as you'll see, this is entirely practical). To help you out, I'll provide information on a couple of small issues that you should keep in mind when doing so.

To cover all this ground, I'll address:

  • Differences Between VBScript and JScript
  • How to Specify Scripting Languages in Visual InterDev
  • Working with Both Languages on the Same Page
  • Getting Updates to the Scripting Languages

Differences Between VBScript and JScript

The most obvious difference between VBScript and JScript is their syntax. VBScript is a subset of Visual Basic—it will look very familiar to you if you've ever used Visual Basic or Visual Basic for Applications (VBA). It is not identical to these languages, however. Because VBScript was specifically designed to work in browsers, it doesn't include features that are normally outside the scope of scripting, such as file access and printing.

JScript, on the other hand, is derived from the group of languages that includes C, C++, and Java. If you have ever worked with C or Java before, the syntax of JScript will be familiar. But even if you do not know those other languages, JScript syntax is not difficult—it has much of the consistency of C and Java without some of the complexities of those languages.

**Note   **In spite of how your local bookstore might stock its computer shelves, JScript and Java are entirely separate languages. Java is a full-blown development language for both Web and non-Web applications. In contrast, JScript is a comparatively light scripting language used primarily for Web page scripting.

JScript and VBScript both accomplish the same goal—to allow you to script your Web pages. Each language supports a few features that the other does not, although these differences are probably not great enough to automatically rule out one language or the other.

More likely, you'll choose your scripting language based on other factors. The single biggest factor is also the most pragmatic: Is the language you choose supported on the platform you want to use? Are you scripting the client or the server and, if so, what browser and server software will your users have?

The following sections provide more detail about the two scripting languages, and suggest some guidelines for choosing them in specific circumstances.

When to Choose VBScript

VBScript is supported primarily on Microsoft platforms. As of this writing, if you want to use VBScript, you must be using one of the following:

  • Server script. If you want to use VBScript as server script (in Active Server Pages), the server must be IIS or a third-party equivalent.
  • Client script. If you want to use VBScript in browser scripts, the browser must be a version of Internet Explorer. Other popular browsers might not support VBScript.

If you are a Microsoft Visual InterDev® user, you're almost certainly already using IIS (or an equivalent), so using VBScript for server script is not a problem. If you are not using IIS, you must be certain that the server includes support for VBScript.

However, the restriction to Internet Explorer for client script is a problem if you are creating a public Web site where you cannot control what browsers people have. Therefore, using VBScript is practical in client script only when you are writing for an audience with a known browser, such as a company intranet.

If you decide that your target platform or platforms can support VBScript, consider the following factors in deciding whether to write individual scripts in VBScript:

  • Error handling. VBScript includes the On Error Resume Next statement for handling exceptions. If you are writing server script, error handling is particularly important because the script runs unattended.
  • Formatting. VBScript includes functions that make it easy to format date, number, and currency data.
  • Easier event handling in Internet Explorer. As in Visual Basic, VBScript allows you to create an "implicit" event handler by simply naming a function with the syntax *object_event—*for example, Button1_onclick. In Internet Explorer, this facility is not available in JScript (although it is supported in other JScript hosts).

When to Choose JScript

JScript is supported by virtually all browsers that allow scripting. It is therefore a natural choice for client scripting if you are writing broad-reach applications for a public Web site. You will also find that because JScript (and its relative, JavaScript) is a widely used, standard scripting language, there are many resources available to help you, both in bookstores and on the Web.

If you want to use JScript for server script, you should check that your server supports it. IIS allows you to use JScript for scripting ASP pages, but not all servers do.

Other factors that might influence your decision to use JScript include:

  • Dynamic execution. A very powerful feature of JScript is that it allows you to create and execute script or evaluate expressions dynamically from within your script. Briefly, your script can write script. This feature is handy when working with DHTML because you can then dynamically manipulate the DHTML document model.
  • Object orientation. JScript uses a prototype-based object structure that allows you to define objects in script. You can extend both built-in and custom-built objects by adding methods and properties to the objects' prototypes.

One caveat when you are working with JScript: It's case sensitive, which can be hard to get used to if you have only used Visual Basic or VBScript.

If you're new to JScript, you will also want to study how to create event handlers in that language. In Internet Explorer, JScript requires that you explicitly link an object and its associated event handler. Typically, you do this by specifying attributes in the object tag that identify the event and the handler function to bind to, as in the following example:

<BUTTON ID="btnSave" LANGUAGE="JavaScript" onclick="btnSave_onclick()">

In other hosts, you can use implicit event binding, but it requires slightly different syntax than in VBScript. The convention for an implicit handler in JScript is this:

<SCRIPT LANGUAGE="JavaScript">
function btnSave::onclick(){
// script here
}
</SCRIPT>

Note that in both examples the LANGUAGE attribute is set to "JavaScript." While Internet Explorer is equally happy with the language names "JScript" and "JavaScript," many other browsers understand "JavaScript" but not "JScript." To be safe, use "JavaScript" if you're not sure the page will be viewed in Internet Explorer.

For more details about creating event handlers in JScript, refer to the Microsoft Visual InterDev documentation on the MSDN Library CD.

How to Specify Scripting Languages in Visual InterDev

Regardless of what scripting language you use, you must specify the language so that the host will know what scripting engine to use to process your script. The exact method you use depends on whether you are working with inline server script or with <SCRIPT> blocks (for either client or server script), and also on what version of Visual InterDev you are using.

Setting the Language for Inline Server Script

If you are using IIS and ASP pages, you can write two types of server script: inline script (script inside <% %> delimiters) and script in <SCRIPT> elements. Typically, inline script allows you to feed the results of scripting into the HTML stream of the page. In contrast, script in <SCRIPT> elements is used to create functions and subroutines that are called from inline script.

Note   It is possible to create script in <SCRIPT> elements that runs as inline script—that is, the script statements are not part of a function or subroutine. However, this practice is not recommended. See the section "Server Script Order of Execution" later in this article for more details.

Setting the language for <SCRIPT> elements is the same for both server and client script. For details, see the section "Setting the Language for a <SCRIPT> Element" later in this article.

All inline script on a page has to be in one language. When you create a new ASP page, the page automatically includes an @ directive that sets the scripting language for inline script. The @ directive might look like this:

<%@ Language="VBScript" %>

The @ directive must be the first inline script command on the page. If this directive is missing, IIS defaults to using VBScript as the inline scripting language.

To change the inline scripting language for a page

  • In Visual InterDev 1.0, edit the page and change the directive to specify a new language, such as "JavaScript."
  • In Visual InterDev 6.0, right-click the page and display the page's Properties dialog box. Then under Default scripting language, choose a new language in the Server box. When you apply the change, the editor updates the @ directive with the appropriate language. If you prefer, you can edit the @ directive yourself manually.

You can also change the default for all new ASP pages. This change won't update existing pages, but it will be in effect for any pages you create from then on.

To change the default language for inline script

  • In Visual InterDev 1.0, choose Options from the Tools menu, and then select the HTML tab. In the Default scripting language area under Active Server Pages, select a language.
  • In Visual InterDev 6.0, right-click the name of the project in the Project Explorer, and then choose Properties. Choose the Editor Defaults tab, and then under Default script language, select a new default.

Setting the Language for a <SCRIPT> Element

Unlike inline server script, the scripting language you use in <SCRIPT> elements can vary on the same page. One block can be in VBScript, another in JScript. (Remember that not all platforms support VBScript.)

**Note   **For notes about things to watch for when you mix scripting languages on the same page, see the section "Working with Both Languages on the Same Page" later in this article.

To specify the language for a <SCRIPT> element

  • In the <SCRIPT> tag, include a LANGUAGE element that specifies the language you want to use. For example, the following <SCRIPT> tag specifies that all the script within that <SCRIPT> element will be in JScript:

    <SCRIPT LANGUAGE="JavaScript">
    function test(){
        alert("testing");
    }
    </SCRIPT>
    

    Note   The LANGUAGE attribute is required by IIS for server script. However, it is optional for client script. If the LANGUAGE attribute is missing, the processor will use the default scripting language. In Internet Explorer for client script, the default is generally the language of the first <SCRIPT> element or, if no language is specified, JScript. However, it is recommended that you do not rely on a default, and instead always explicitly set the language for a <SCRIPT> element.

You cannot mix VBScript and JScript within a single <SCRIPT> element. If you want to use both, you will need to have (at least) two <SCRIPT> elements in your page.

Both Visual InterDev 1.0 and Visual InterDev 6.0 include tools that generate script automatically. In Visual InterDev 1.0, you can use the Script Wizard to generate script. In Visual InterDev 6.0, there are a couple of script-generation tools:

  • The Script Block command on the page's right-click menu inserts a skeleton <SCRIPT> element at the point that you click.
  • The Script Outline creates skeleton event handlers when you double-click the name of an event.

The various script-generating tools decide what language to use based on settings that you make. You can change the default language for scripting tools in an individual page.

To set the language for the Script Wizard in Visual InterDev 1.0

  • Choose Options from the Tools menu, and then select the HTML tab. In the Default scripting language area under Script Wizard, select a language.

To set the language in one page for script generation tools in Visual InterDev 6.0

  • Right-click the page and display the page's Properties dialog box. Then under Default scripting language, choose a new language. You can set a language for both server script blocks and client script blocks.

    Note   The setting used for generating server script blocks is also used to set the language for inline script. If you want to use one language for inline script and another when you use the tools to generate server script blocks, you will have to change the language for one or the other manually.

You can also change the default for your project so that all pages you create already have the default language set for the scripting tools.

To change the default language for script-generating tools in a Visual InterDev 6.0 project

  • Right-click the name of the project in the Project Explorer, and then choose Properties. Choose the Editor Defaults tab, and then under Default script language, select a new default.

    Note   The setting for generated server script blocks is also used to set the language for inline script. If you want to use one language for inline script and another when you use the tools to generate server script blocks, you will have to change the language for one or the other manually.

Working with Both Languages on the Same Page

I hope I've made it clear by now that you can use both scripting languages on the same page. Let's review: Why would you want to do this? There are a couple of reasons:

  • You might want to take advantage of a language-specific feature in just one routine, but create the rest of your script in another language.
  • You might be working with generated code that isn't in your preferred language. For example, design-time controls might generate code in JScript, but you might prefer working in VBScript.

For the most part, you can mix and match scripting languages on the same page without any problems. A script in one language can call routines in another language and share global variables with scripts in another language. There are just a few issues that arise sometimes, as I'll now explain.

Including Parentheses in a VBScript Call

When you are calling a JScript function from VBScript, be sure to include the parentheses in the call, even if the function doesn't require parameters. For example, a call should look like this:

retVal = callJSFunction()

If you neglect to include the parentheses, the return value of the function will not be the value you expect, but an object containing the function itself!

Server Script Order of Execution

Inline server script runs sequentially, top to bottom. You can define callable routines (functions or subroutines) in server script, and they will be called as needed.

All inline script has to be in the same language—namely, the language specified in the @ directive at the top of the page. Therefore, you can't mix scripting languages in inline script.

"But wait!" you might say. It is theoretically possible to put inline-like script into a <SCRIPT> element—that is, have script in the element that is not part of a function or subroutine, as in the following example:

<% Response.Write("Some inline script<BR>")%>
<SCRIPT LANGUAGE="VBScript" RUNAT="Server">
    Response.Write("Script in a SCRIPT element<BR>")
</SCRIPT>

Yes, you can do this. However, you are then at the mercy of the order of execution of the IIS ASP processor. For example, if you create server script and run it in IIS 4.0, you'll find this execution order:

  1. Script in <SCRIPT> elements in nondefault languages
  2. Inline script
  3. Script in <SCRIPT> elements in the default language

Because this order seems to rely heavily on the load sequence for the ActiveX language engines, and because the ASP processor in IIS might change in future releases, we strongly discourage you from relying on this sequence. Either use <SCRIPT> elements only for functions or subroutines, or for code whose execution sequence doesn't matter. (Is there such code?)

Ordering Script Blocks

When you are mixing languages, the order in which <SCRIPT> blocks appear in the page can make a difference as to whether they work properly. Consider this simple case of an inline VBScript script calling a function written in JScript:

<SCRIPT LANGUAGE="VBScript">
    ' Calls a JScript function
    aNumber = 2
    doubledNumber = doubleMe(aNumber)
    document.write("The answer is " & doubledNumber)
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
function doubleMe(aNumber){
    return aNumber * 2;
}
</SCRIPT>

This won't work. More specifically, the document.write statement will write an empty string to the page. Why? Because at the time the VBScript block is being processed, the following JScript <SCRIPT> block has not yet been read, parsed, and made available to the page. When the browser processes the script blocks in the page, it works from top to bottom.

In this case, simply reversing the order of the script blocks solves the problem. And in fact, this type of scenario is not all that common—for the most part, <SCRIPT> blocks contain functions and subroutines that will not be called until the page has been fully loaded and all elements are available. Nonetheless, you should keep in the back of your mind the fact that pages are processed linearly and that <SCRIPT> blocks in different languages are processed separately.

Case Sensitivity and Naming Conventions

JScript is case sensitive: You have to use the correct combination of uppercase and lowercase letters not just for every JScript keyword, but for everything in the JScript namespace. This includes all keywords in any object models you use. For example, when using the ASP Response object, you have to use it exactly that case (for example, Response.Write) or JScript will stubbornly refuse to believe that any such thing exists. Similarly, if you are writing a handler for the DHTML onclick event, JScript will not recognize it in the style (Onclick) frequently used in Visual Basic.

VBScript, of course, is not case sensitive. To a certain degree, this indifference to case applies even when you are using VBScript to access elements written in JScript. The following trivial example shows two scripts. The first is written in JScript and includes a global variable (ctr) and a mindless little function (doubleMe). The second script is in VBScript and is a button handler that calls the JScript function and reports the value of the global variable:

<SCRIPT LANGUAGE=javascript>var ctr;function doubleMe(aNumber){    // 
Initialize value of global counter    if(parseInt(ctr)){
        ctr = ctr + 1;}
    else{
        ctr = 1;
    }
    return aNumber * 2;
}
</SCRIPT>

<SCRIPT LANGUAGE="vbscript">
Function btn1_onclick()
    numberToDouble = 12
    alert("The doubled number = " & DoubleMe(numberToDouble))
    alert("You have doubled the number " & Ctr & " times.")
End function
</SCRIPT>

In the VBScript script, I deliberately did not use the correct case when referring to the doubleMe function and the ctr variable, but the example runs fine.

That's the good news. The bad news is that there are some situations in which you do indeed need to be aware of case issues:

  • If the JScript scripts on the page include elements that are distinguished only by case, for example, a function called Timer() and a global variable called timer. Mind you, this might not be good coding practice, but sometimes your page comes with preexisting code.
  • If you are passing JScript element names as string parameters in a function call.

If JScript includes elements distinguished only by case, VBScript allows you to reference them as usual (that is, without case sensitivity). However, VBScript will seize on the first, non-case-sensitive match and will thereafter recognize only that JScript element. In other words, if VBScript first finds the function called Timer(), it will not find the global variable called timer, and vice versa. This is true even if you carefully distinguish the two in your VBScript code, because VBScript will effectively treat the names as if they were all one case anyway. Unfortunately, there is no real workaround here except (if possible) to tweak the JScript code so it does not use this subtle distinction between elements.

The issue of passing element names as parameters might not be common except in specialized circumstances. One such circumstance is the scripting object model in Visual InterDev 6.0. I'll use that as an illustration, but in principle the issue can come up any time you use a similar design.

The scripting object model for Visual InterDev 6.0 is all written in JScript. You can write your own code in VBScript to interact with the scripting object model using VBScript case-sensitivity conventions. However, sometimes you don't directly call a method. Instead, you pass the name of a method to a JScript function, which will call the method for you.

A good example is the advise method, which allows you to bind a method to a specific event. When you call this method, you pass to it the name of a method that should be called when the event fires. The following binds a button's onmouseover event to the changecaption() event handler:

<SCRIPT LANGUAGE="VBScript">Function setAdviseMethods()
    Btn1.advise("onmouseover", "changecaption()")
End Function
</SCRIPT>

Because you are passing these names as strings to a JScript function, you must get the case right. JScript will later evaluate the names using its own case-sensitive rules, and if the case isn't right, it will, as always, fail to find them.

Passing Arrays from VBScript to JScript

Occasionally a VBScript routine will pass an array as one of its parameters or as its return value. You can call such a routine from JScript, but must convert the VBScript array into a usable JScript array. To do so, create a VBArray object in your JScript function and convert it to a JScript array using toArray.

Note   Because JScript does not support multidimensional arrays, if the original VBScript array was multidimensional, the toArray method converts it to a single-dimension JScript array.

The following example includes a VBScript script that creates an array and a JScript script that illustrates how to get and use the array:

<SCRIPT LANGUAGE="VBSCRIPT">
Function makeArrayVB()
    ' Creates a VBScript array
    dim anArray(1,1)
    anArray(0,0) = "0,0"
    anArray(0,1) = "0,1"
    anArray(1,0) = "1,0"
    anArray(1,1) = "1,1"
    makeArrayVB = anArray
End Function

<SCRIPT LANGUAGE="JavaScript">
// Accesses a VBScript array within a JScript script
function getVBArray(){
    var arrayObj;
    var jsArray;
    arrayObj = makeArrayVB();
    jsArray = VBArray(arrayObj).toArray();
    alert("VBScript array length = " + jsArray.length);
    // Displays the contents of the array
    for(i=1;i<=jsArray.length;i++){
       alert(jsArray[i-1]);
    }
}
</SCRIPT>

Unfortunately, in the current release of VBScript (4.0), the reverse is not possible: You cannot convert a JScript array into a VBScript one. If you're faced with a JScript routine that passes an array, you have these options:

  • Write the calling routine in JScript as well.
  • Rewrite the JScript routine in VBScript.
  • If possible, alter the JScript array to pass a different structure, such as a delimited string, that VBScript can handle. For example, you can use the toString function to turn an array into a comma-delimited string. Then in VBScript, you can use the Split function to peel off individual elements. Obviously, this is not a practical solution in many cases, but can sometimes be worthwhile.

Getting Updates to the Scripting Languages

VBScript and JScript are not static languages. Both language engines are updated regularly with new features and to address (ahem!) anomalies that have been discovered. Because both languages are actually implemented as ActiveX components, you can update them the same as you update any control. After you've installed a new language engine, any application that calls the engine—such as Internet Explorer or Visual InterDev—will call the new engine whenever it's time to run some script.

For information about the state of the language engines, how you can get updates, and a lot more about scripting generally, be sure to visit the Microsoft Scripting Web site at https://msdn.microsoft.com/scripting/. In the meantime, enjoy your scripting adventures!