The <script> tag in HTML is used to embed or reference JavaScript code in a web page. It allows you to add dynamic behavior, interactivity, and logic to the page.
Ways to Use <script>
- Inline JavaScript
<script>
alert('Hello, world!');
</script>
- External JavaScript File
<script src="script.js"></script>
src→ URL/path of the external JS file.- Usually placed at the end of
<body>for faster page load.
Important Attributes
| Attribute | Purpose |
|---|---|
src |
Link to an external JavaScript file |
async |
Load the script asynchronously without blocking HTML parsing |
defer |
Load script after HTML parsing is complete |
type |
Type of script (default is text/javascript) |
crossorigin |
Handle CORS requests for external scripts |
Example with defer
<head>
<script src="script.js" defer></script>
</head>
- Script runs after the HTML is fully parsed, improving performance.
💡 In Short:
The
<script>tag is used to add JavaScript functionality to a web page, either inline or via an external file, enabling interactivity and dynamic behavior.