Script Tag in HTML
The HTML Script Tag <script> is used to embed or reference JavaScript inside an HTML page. JavaScript makes web pages dynamic and interactive — handling user actions, animations and data updates.
What is the Script Tag?
- The
<script>tag inserts client-side JavaScript into HTML. - Internal scripts are written between
<script> ... </script>tags. - External scripts use the
srcattribute to link a.jsfile. - Modifiers like
asyncanddefercontrol execution timing.
Why Use the Script Tag?
Interactivity
Add dynamic behavior — clicks, animations, validation.
DOM Updates
Modify webpage content without reloading.
Plug Libraries
Include jQuery, React, Vue or any JS library.
Logic
Handle business logic and calculations in the browser.
API Calls
Fetch data from servers using AJAX or Fetch.
Games & Apps
Build full browser games and web apps.
Script Tag Syntax
- Internal:
<script> alert('Hi'); </script> - External:
<script src="app.js"></script> - Async:
<script src="a.js" async></script> - Defer:
<script src="a.js" defer></script> - Module:
<script type="module" src="a.js"></script>
Script Tag Example
<!DOCTYPE html>
<html>
<body>
<h1 id="msg">Hello</h1>
<button onclick="greet()">Click Me</button>
<script>
function greet() {
document.getElementById('msg').innerText = 'Welcome to PBA Institute!';
}
</script>
</body>
</html>
Code Explanation
| HTML Part | Meaning |
|---|---|
| <script> | Container for JavaScript code. |
| id="msg" | Unique identifier targeted by JS. |
| onclick="greet()" | Calls the greet() function when button is clicked. |
| document.getElementById | Finds the element by id. |
| innerText | Replaces the text inside the element. |
Script Tag Attributes
Use Cases
- Form validation: Validate before submitting to server.
- Animations: Smooth transitions and effects.
- API integration: Fetch data from servers.
- Interactive UI: Sliders, dropdowns, modals.
Practice Questions
- Display an alert when the page loads.
- Use a button to change paragraph text via JavaScript.
- Link an external
app.jsfile to your HTML. - Use
deferto load a script after HTML parses.
Frequently Asked Questions
Where should I place the script tag?
Best practice: at the end of <body> or in <head> with defer.
What is the difference between async and defer?
async runs as soon as it loads; defer waits until HTML is parsed.
Can I use multiple script tags?
Yes, you can have multiple scripts on one page.
Should I use external JS?
Yes, for maintainability and browser caching benefits.
Conclusion
The HTML Script Tag is the bridge between static HTML and dynamic JavaScript. Master internal, external, async and defer scripts to build powerful, interactive web pages.
Additional Tips
- Use external files: Keep HTML clean and JS reusable.
- Prefer defer: Improves page load performance.
- Use modules: Organize large code with ES6 modules.
- Minify in production: Reduces file size.