The JavaScript computer language is used to create scripts this represent a small part into a larger program. Usually a script is part of a HTML web page but can also be an separated file.

Where to put the script?

We can use tags: <script> JavaScript Code </script> to mark a script into HTML pages. One HTML page can contain many scripts. Each script must be enclosed into tags.

Default scripting language for web pages is JavaScript but it is possible to use other computer languages in HTML web pages using the tag <script>.

Script location in <head> or <body>

In HTML we neste one tag in other tag. The <script> can be nested in the <head> tag into HTML pages or <body> tag.

Note: Web developers preffer to implement JavaScript in the <body> region of HTML. This is to allow a faster rendering of the page. JavaScript must be compiled and is better to compile the script after the page is loaded.

Example1:

In this example JavaScript is stored in <head>.

<!DOCTYPE html>
<html>

<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Example2:

In this example JavaScript is located in the <body>

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

 

External Scripts

We can create JavaScript files with extension .js that are loaded in HTML pages using tag script with attribute src: like this:

<script src=”sourge_file.js”>

 

Example3:

In this example  JavaScript myFunction is hooked to an click event of the button. Whe user press the button the function is executed.

<!DOCTYPE html>
<html>
<body>

<h1>External JavaScript</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p>

<script src="myScript.js"></script>

</body>
</html>

//JavaScript source file is external

 

Externa file: myScript.JS contain the declaration for function myFunction().

function myFunction() {
     document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External JavaScript Advantages

Placing JavaScripts in external files has some advantages:

  • It separates HTML and code so HTML is smaller
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads
  • External JavaScript functions can be reused in many HTML pages