Search
Close this search box.
Search
Close this search box.

Running a JavaScript Program

Before you even start writing your first JavaScript program, you’ll have to know how to run it.

To include some JavaScript on an HTML page, we have to include a <script> tag inside the head of the document. A script doesn’t necessarily have to be JavaScript, so we need to tell the browser what type of script we’re including by adding a type attribute with a value of text/javascript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>My first javascript program</title>
        <script type="text/javascript">
            // you enter here all the javascript code
        </script>
    </head>
</html>

You can put as much JavaScript code as you want inside that <script> tag—the browser will execute it as soon as it has been downloaded.

Even though it’s nice and easy to just type some JavaScript straight into your HTML code, it’s preferable to include your JavaScript in an external file. This approach provides several advantages:

  • It maintains the separation between content and behavior (HTML and JavaScript).
  • It makes it easier to maintain your web pages.
  • It allows you to easily reuse the same JavaScript programs on different pages of your site.

To reference an external JavaScript file, you need to use the src attribute on the <script> tag:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>My first javascript program</title>
        <script type="text/javascript" src="example.js"></script>
    </head>
</html>

Any JavaScript that you might have included between your <script> and </script> tags can now be put into that external file and the browser will download the file and run the code.

The file can be called whatever you want, but the common practice is to include a .js extension at the end of it.

It’s possible to include as many external scripts on your page as you want:

<script type="text/javascript" src="library.js"></script>
<script type="text/javascript" src="more.js"></script>
<script type="text/javascript" src="example.js"></script>

This capability is what makes JavaScript libraries, where you include a standard library file on your page alongside other code that uses the contents of that library, possible.

Every time you load a page with JavaScript on it, the browser will interpret all of the included JavaScript code and figure out what to do with it. If you’ve loaded a page into your browser, and then you make some changes to that page’s JavaScript (either on the page itself or in an external file), you’ll need to refresh the page before
those changes will be picked up by the browser.