CA Resources

Where to Insert

Learn where and how to place JavaScript in your HTML.

JavaScript can be placed in the head and body section

We can place JavaScript both in the <head> and <body> sections of a page by using the <script></script> elements.

<!DOCTYPE html>
<html>
  <head>
    <script> 
      function myFunction() { 
        document.getElementById("demo").innerHTML = "Paragraph changed!"; 
      } 
    </script> 
  </head>
  <body>
    <h2>Demo JavaScript in Head</h2>
    <p id="demo">A paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
  </body>
</html>

JavaScript can be external from the HTML file

JavaScript can also be placed in external files just like external CSS. External scripts are practical when the same code is used in many different web pages.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag. Users can place an external script reference in <head> or <body>. The script will behave as if it was located exactly where the <script> tag is located.

JavaScript files have the file extension of .js.

myScript.js

External JavaScript cannot contain <script> tags.

The use of <script> tag will be inside the html file.

Connecting to external JavaScript

index.html
myScript.js
js/myScript.js
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
index.html
<!DOCTYPE html>
<html>
  <body>
    <h2>Demo External JavaScript</h2>
    <p id="demo">A paragraph.</p>
    <button type="button" onclick="myFunction()">Try it</button>
    <p>This exmaple links to "myScript.js"</p>
    <p>(myFunction is stored in "myScript.js")</p>
    <script src="js/myScript.js"></script> 
  </body>
</html>

Advantages of using external JavaScript

Placing scripts in external files offer some advantages like:

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

External References

An external references can be referenced in 3 different ways.

  • With a full URL website link.
  • With a file path /js/javascript.js
  • With any path javascript.js
Edit on GitHub

Last updated on

On this page