Internal Script Embedding
JavaScript can be embedded directly within HTML using script tags located inside the head section.
<html>
<head>
<meta charset="utf-8" />
<title>Example Page</title>
<script type="text/javascript">
function displayMessage() {
alert("Hello World");
}
</script>
</head>
<body>
<input type="button" value="Click Me" onclick="displayMessage()" />
</body>
</html>
This approach has limitations:
- JavaScript code is confined to a single HTML document, limiting reusability and maintainability.
- Mixing JavaScript and HTML reduces readability.
External Script Linking
External JavaScript files can be referenced using the src attribute of the script tag.
<html>
<head>
<meta charset="UTF-8">
<title>External Script Example</title>
<script type="text/javascript" src="js/external.js"></script>
<script type="text/javascript" src="js/another.js"></script>
</head>
<body>
<input type="button" value="Trigger Function 1" onclick="functionOne()" />
<input type="button" value="Trigger Function 2" onclick="functionTwo()" />
<input type="button" value="Trigger Function 3" onclick="functionThree()" />
<script>
function functionThree() {
alert("Always Here");
}
</script>
</body>
</html>
Benefits of external linking:
- Improved code reusability
- Easier maintenance
Key considerations:
- Multiple external scripts can be loaded per page
- Each script requires its own script tag
- An individual script tag cannot contain both internal and external references