About Lesson
External JavaScript (Linking to an External File)
In the external JavaScript method, you place your JavaScript code in a separate .js file and link to it using the <script> tag with a src attribute in your HTML file. This method is preferred for larger projects as it keeps HTML and JavaScript code separate, making both easier to maintain.
Example:
HTML File:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript Example</title>
<script src="app.js"></script>
</head>
<body>
<button onclick="showMessage()">Click Me</button>
</body>
</html>
- Head Section: Placing the script inside the <head> section can cause the script to run before the page content is fully loaded.
- End of Body: It’s common to place the <script> tag just before the closing </body> tag. This ensures that the HTML content loads first, and then the script executes.
JS File (External JavaScript File) – App.js:
JavaScript
function showMessage() {
alert('Hello from External JavaScript!');
}
- Advantages of External JavaScript:
- Code reusability: You can use the same .js file across multiple HTML files.
- Separation of concerns: HTML handles structure, CSS handles style, and JavaScript handles behavior.
- Easier to maintain and debug.
When to Use Which Method?
- Inline JavaScript: Best for very simple tasks, but avoid using it for larger projects.
- Internal JavaScript: Useful for small projects or one-off scripts, but can clutter your HTML file.
- External JavaScript: Best practice for most projects, especially when the script is used across multiple pages or the codebase is large.