You can include JavaScript in an HTML page in three main ways:
- Inline JavaScript – Directly within an HTML tag.
- Internal JavaScript – Inside
<script>tags within the HTML document. - External JavaScript – In a separate
.jsfile linked to the HTML page.
Here’s an example demonstrating all three methods:
1. Inline JavaScriptJavaScript is added directly to an HTML element using the
2. Internal JavaScriptonclick attribute.Explanation:
- When the button is clicked, the
onclickattribute triggers thealert()function directly.
JavaScript is placed inside the HTML file but within
3. External JavaScript<script> tags.Explanation:
- The
<script>tag is placed within the same HTML file, but the JavaScript logic is separate from the button.
JavaScript is written in a separate file (
script.js) and linked to the HTML using the <script> tag.HTML (index.html):
JavaScript (script.js):
Explanation:
- The JavaScript code is stored in
script.js. - The HTML file links to it using the
<script src="script.js"></script>tag.
Best Practices:
- Use external JavaScript for better code organization and reusability.
- Place
<script>tags before the closing</body>to ensure the HTML loads before JavaScript is executed, improving performance.