The Wayback Machine - https://web.archive.org/web/20250101003505/https://www.geeksforgeeks.org/where-to-put-javascript-in-an-html-document/
Open In App

How to Add JavaScript in HTML Document?

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

To add JavaScript in HTML document, several method can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.

Inline JavaScript

You can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other event handler attributes.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Inline JavaScript
    </title>
</head>

<body>
    <h2>
        Adding JavaScript in HTML Document
    </h2>

    <button onclick="alert('Button Clicked!')">
        Click Here
    </button>
</body>

</html>

Output

Inline-JavaScript

For a more comprehensive guide on integrating JavaScript with HTML, explore our JavaScript Course, which covers everything from basic scripting to building interactive and dynamic web pages.

Internal JavaScript (Within <script> Tag)

You can write JavaScript code inside the <script> tag within the HTML file. This is known as internal JavaScript and is commonly placed inside the <head> or <body> section of the HTML document.

1. JavaScript Code Inside <head> Tag

Placing JavaScript within the <head> section of an HTML document ensures that the script is loaded and executed as the page loads. This is useful for scripts that need to be initialized before the page content is rendered.

Example: This example shows the addition of a script file inside the head section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Add JavaScript Code inside Head Section
    </title>

    <script>
        function myFun() {
            document.getElementById("demo")
                .innerHTML = "Content changed!";
        }
    </script>
</head>

<body>
    <h2>
        Add JavaScript Code
        inside Head Section
    </h2>

    <h3 id="demo" style="color:green;">
        GeeksforGeeks
    </h3>

    <button type="button" onclick="myFun()">
        Click Here
    </button>
</body>

</html>

Output

JavaScript inside the <head> example output” width=”460â€ģ height=”204â€ģ loading=”lazy”></p>
<h3 id=2. JavaScript Code Inside <body> Tag

JavaScript can also be placed inside the <body> section of an HTML page. Typically, scripts placed at the end of the <body> load after the content, which can be useful if your script depends on the DOM being fully loaded.

Example: This example shows showing the addition of a script file inside the body section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Add JavaScript Code inside Body Section
    </title>
</head>

<body>
    <h2>
        Add JavaScript Code
        inside Body Section
    </h2>

    <h3 id="demo" style="color:green;">
        GeeksforGeeks
    </h3>

    <button type="button" onclick="myFun()">
        Click Here
    </button>

    <script>
        function myFun() {
            document.getElementById("demo")
                .innerHTML = "Content changed!";
        }
    </script>
</body>

</html>

Output

JavaScript inside <Body> example output” width=”460â€ģ height=”204â€ģ loading=”lazy”></p>
<h2 id=External JavaScript (Using External File)

For larger projects or when reusing scripts across multiple HTML files, you can place your JavaScript code in an external .js file. This file is then linked to your HTML document using the src attribute within a <script> tag.

Example: This example shows showing the linking of an external script file inside the head section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        External JavaScript
    </title>
    <script src="script.js"></script>
</head>

<body>
    <h2>
        External JavaScript
    </h2>

    <h3 id="demo" style="color:green;">
        GeeksforGeeks
    </h3>

    <button type="button" onclick="myFun()">
        Click Here
    </button>
</body>

</html>
JavaScript
/* Filename: script.js*/

function myFun () {
    document.getElementById('demo')
        .innerHTML = 'Content Changed'
}

Output:

External JavaScript example output

Advantages of External JavaScript

  • Faster Page Load Times: Cached external JavaScript files don’t need to be reloaded every time the page is visited, which can speed up loading times.
  • Improved Readability and Maintenance: Keeping HTML and JavaScript separate makes both easier to read and maintain.
  • Separation of Concerns: By separating HTML (structure) and JavaScript (behavior), your code becomes cleaner and more modular.
  • Code Reusability: One external JavaScript file can be linked to multiple HTML files, reducing redundancy and making updates easier.

Asynchronous and Deferred JavaScript

JavaScript can be loaded asynchronously or deferred to optimize page performance, especially for larger scripts. By default, JavaScript blocks the rendering of the HTML page until it is fully loaded, but using async or defer can help improve load times.

1. async Attribute

The async attribute loads the script asynchronously, meaning the script will be downloaded and executed as soon as it is available, without blocking the page.

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

2. defer Attribute

The defer attribute delays the execution of the script until the entire HTML document has been parsed. This is particularly useful for scripts that manipulate the DOM.

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

How to Reference External JavaScript Files?

We can reference an external script in three ways in javascript:

  • By using a full URL:
src = "https://www.geeksforgeek.org/js/script.js"
  • By using a file path:
src = "/js/script.js"
  • Without using any path:
src = "script.js"


Next Article

Similar Reads

three90RightbarBannerImg