Adding JavaScript in HTML Document (original) (raw)
Last Updated : 13 Jun, 2026
JavaScript can be included in an HTML document to make web pages interactive and dynamic. It allows you to handle user actions, update content without reloading the page, and control browser behavior.
- JavaScript can be added using the
Add JavaScript Code inside Head Section
GeeksforGeeks
Click Here`
2. JavaScript Code Inside Tag
JavaScript can also be placed inside the section of an HTML page. Typically, scripts placed at the end of the load after the content, which can be useful if your script depends on the DOM being fully loaded.
HTML `
Add JavaScript Code inside Body Section
GeeksforGeeks
Click Here`
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
External JavaScript
GeeksforGeeks
Click HereJavaScript/* Filename: script.js*/
function myFun () { document.getElementById('demo') .innerHTML = 'Content Changed' }
`
**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.
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"
Also Check: