JavaScript in HTML
There are 3 main ways to add javascript to html:
- Inline JavaScript (Inside HTML tags)
- Internal JavaScript (Inside <script> tags)
- External JavaScript File
Inline JavaScript
You can place JavaScript code directly within an HTML element by using event handler attributes like onclick or ondblclick.
Example
Run Code<html>
<head></head>
<body>
<h2>
Adding JavaScript in HTML Document
</h2>
<button onclick="alert('Button Clicked!')">
Click Here
</button>
</body>
</html>
Internal JavaScript
You can write JavaScript code inside the <script> tag within the HTML file. The <script> tag can be placed in the <head>, in the <body>, or in both. However, for optimal performance, it’s best to place it at the end of the <body>.
The browser reads and executes <script> tags in the order they appear. If you place a script in the <head>, loading and executing the script may block the loading of the HTML content. Therefore, to optimize performance and page display speed, people often put scripts at the end of the <body> section (or use defer/async in <head>).
Example
Run Code<html>
<head></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>
External JavaScript
As your project grows, it's better to separate JavaScript code into its own .js file for easier maintenance and management. You can then include it in your HTML using the <script> tag with the src attribute.
Example
Run Code<html>
<head>
<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>
ES Modules
Modern browsers support ES modules, which allow imports and exports between files.
Supports import/export, scoped variables, async loading. Requires modern browsers.
Example
Run Code<script type="module">
import { greet } from './greet.js';
greet('World');
</script>
<script type="module" src="main.js"></script>
Defer and Async Loading
Used when linking external JS files to control load timing.
- defer: runs after HTML is parsed, in order.
- async: runs as soon as loaded (order not guaranteed).
Improves performance and prevents blocking the page load.
Example
Run Code<script src="main.js" defer></script>
<script src="analytics.js" async></script>
Dynamic Script Injection
You can add scripts to the page dynamically using JavaScript.
Useful for loading scripts on demand. Harder to debug or control timing.
Example
Run Codeconst script = document.createElement('script');
script.src = 'extra.js';
document.body.appendChild(script);