JavaScript Introduction | Overview | Applying JavaScript

How to Apply JavaScript

There are the following ways to apply JavaScript code to an HTML document.

  1. Apply as internal JavaScript code
  2. Apply as an external JavaScript file

JavaScript Code

JavaScript code can be inserted into an HTML document by using the <script> tag.

Syntax

<script>
    document.getElementById("text").innerHTML = "Welcome!";
</script>

JavaScript code inserted this way can be placed in the <head> tag, the <body> tag, or both in the HTML document.

The following example inserts JavaScript code into the <head> tag of an HTML document.

<head>
    <meta charset="UTF-8">
    <title>JavaScript Apply</title>
    <script>
        function printDate() {
            document.getElementById("date").innerHTML = Date();
        }
    </script>
</head>

The following example inserts JavaScript code into the <body> tag of an HTML document.

<body>
    <p>With JavaScript, you can easily access current date and time information!</p>
    <button onclick="printDate()">Show the current date and time!</button>
    <p id="date"></p>
    <script>
        function printDate() {
            document.getElementById("date").innerHTML = Date();
        }
    </script>
</body>

As shown in the two examples above, there is no behavioral difference between inserting JavaScript code into the <head> tag and inserting it into the <body> tag.

External JavaScript File

JavaScript code can be created and inserted not only inside an HTML document, but also as an external file.

Externally written JavaScript files are saved with the .js extension. Include the external JavaScript file with the <script> tag on every web page where you want to apply that JavaScript file.

example.js

function printDate() {
    document.getElementById("date").innerHTML = Date();
}
<head>
    <meta charset="UTF-8">
    <title>JavaScript Apply</title>
    <script src="/examples/media/example.js"></script>
</head>

Using an external JavaScript file separates the JavaScript code that implements web behavior from the HTML code that handles web content. This makes both the HTML code and JavaScript code easier to read and easier to maintain. Also, external JavaScript files can be read ahead of time by the web browser, so the loading speed of the web page also becomes faster.