How to Link JavaScript File to a Separate HTML File?
Linking a JavaScript file to an HTML document creates a connection that enables the execution of JavaScript code within the webpage. This is commonly achieved using the <script>
tag in the HTML file, where the src
attribute specifies the path to the external JavaScript file. Approximately 90% of modern websites use JavaScript to enhance interactivity and functionality, making this linking process a fundamental part of web development.
1. Using src attribute in script Tag
We use the src attribute within the <script> tag in the HTML file to specify the source file (JavaScript) location. The external JavaScript file is then linked to the HTML document, enabling the execution of its code.
Syntax:
<script src="js-file-name"></script>
Example: The below example uses the src attribute in <script> Tag to link the javascript file to a separate HTML file.
<!DOCTYPE html>
<html>
<head>
<title>Link JavaScript file
to a separate HTML file
</title>
</head>
<body>
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>Using src attribute in
<script> Tag
</h3>
<button onclick="h1ChgFn()">
Change Heading
</button>
<script src="script.js"></script>
</body>
</html>
// script.js
function h1ChgFn() {
let heading1 = document.querySelector('h1');
heading1.textContent = 'GFG';
}
Output:
2. Using ECMAScript Modules
This approach uses ECMAScript Modules to link a JavaScript file to an HTML document. The import statement in the JavaScript file specifies the module's path. This method allows for cleaner and more organized code.
Syntax:
import { functionName, variableName } from './file.js';
Example: The below example uses the ECMAScript Modules to link the javascript file to a separate HTML file.
<!DOCTYPE html>
<html>
<head>
<title>Link JavaScript using ECMAScript Modules</title>
</head>
<body>
<script type="module">
import { initialize } from './script.js';
initialize();
</script>
</body>
</html>
// script.js
let headingColor = 'green';
export function initialize() {
document.addEventListener('DOMContentLoaded', function () {
let heading1 = document.createElement('h1');
heading1.textContent = 'GeeksforGeeks';
heading1.style.color = headingColor;
document.body.appendChild(heading1);
let heading3 = document.createElement('h3');
heading3.textContent = 'Using ECMAScript Modules';
document.body.appendChild(heading3);
let button = document.createElement('button');
button.textContent = 'Change Color';
button.addEventListener('click', function () {
changeColor(heading1);
});
document.body.appendChild(button);
});
}
function changeColor(element) {
headingColor = headingColor === 'green' ? 'red' : 'green';
element.style.color = headingColor;
}
Output: