The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.


JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.


Example function myFunction() { document.getElementByIHTML Sandbox — click to edit


JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.


Demo JavaScript in Body A Paragraph Try it function myFuHTML Sandbox — click to edit


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {

 document.getElementById("demo").innerHTML = "Paragraph changed.";

}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:


Example

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


Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads