<script> Tag in HTML | JavaScript Integration
The <script> tag in HTML is used to include client-side JavaScript in an HTML document. This tag allows you to embed JavaScript code within an HTML page or link to an external JavaScript file. It can be placed in the <head> or <body> section of the HTML document.
Key Points on <script> Tag:
- The <script> tag is used for including JavaScript code in an HTML document.
- JavaScript code inside the <script> tag is executed when the page loads (for inline scripts) or when the external script file is loaded (for external scripts).
- It is important to place the <script> tag either at the end of the <body> section or in the <head> section to control when the script runs.
- External JavaScript files can be linked using the src attribute.
- The <script> tag can contain JavaScript code or a reference to an external JavaScript file.
Syntax of <script> Tag:
Syntax Example
<script>
// Your JavaScript code here
</script>
OR
<script src="path/to/your/script.js"></script>
Example of <script> Tag in HTML:
This example demonstrates how to use the <script>
tag to include JavaScript in an HTML page.
Code Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML <script> Tag Example</title>
</head>
<body>
<h1>Welcome to the Script Tag Example</h1>
<script>
alert("Hello, welcome to the page!");
</script>
</body>
</html>
Output
External Script Example:
This example demonstrates how to link an external JavaScript file using the <script>
tag.
Code Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Script Example</title>
</head>
<body>
<h1>External JavaScript Example</h1>
<script src="example.js"></script>
</body>
</html>
The <script>
tag is essential for integrating JavaScript into an HTML document. It allows for both inline JavaScript and linking to external JavaScript files. Proper placement of the <script>
tag ensures that your JavaScript code runs at the appropriate time, contributing to a smooth and interactive user experience. Whether used for form validation, dynamic content updates, or interaction with the user, JavaScript plays a key role in modern web development.