Search this site...

Running JavaScript

The browser is responsible for running JavaScript. Thus the output from JavaScript is going to be more responsive as the data does not need to travel to or from server. A web browser runs JavaScript when a web page is downloaded or in response to an event.

JavaScript code can be placed either in an HTML file or an external file. So how do you decide where do you place your code? If your JavaScript code is small and cannot be used in any other web page, then, you should consider placing your code directly in the HTML document that uses it. If, on the other hand, your JavaScript is long and/or used very by many HTML documents, then, you should create a separate JavaScript file.

Because you can insert JavaScript code inside an HTML file, it needs to be distinguished from the rest of the text or code on the page. To separate your JavaScript commands from HTML commands or regular text on the page, insert your JavaScript code inside the opening <script> and closing </script> tag. For example,

<script language="JavaScript">
JavaScript commands

Because there are different client-side languages, we need to indicate to the browser which language we are using in our scripts. To indicate the scripting language, we added the language attribute to the <script> tag. Since we are using JavaScript, we set the language tag to JavaScript. If you omit the language tag from your <script> tag, the browser will assume that your code is written in JavaScript.

If you place your scripting code outside of the HTML page, you still use the <script> tag but then just add the src attribute. The value of src attribute tells the browser where your JavaScript code is located. For instance,

<script language="JavaScript" src="JavaScript/displayDate.js">

indicates that we are using JavaScript language and the JavaScript commands are located in a folder called JavaScript and a file called displayDate.js. A ".js" file extension indicates a JavaScript file.