What is the Script Tag?
The <script> tag is used to embed or link JavaScript in an HTML document to add interactivity and dynamic behavior.
Inline Script
External Script
Script Placement
Scripts can be placed in the <head> or before the closing </body> tag. Placing scripts at the bottom improves page loading performance.
Async Attribute
The async attribute loads the script asynchronously without blocking HTML parsing.
Defer Attribute
The defer attribute ensures the script executes after the HTML document is fully parsed.
Async vs Defer
| Feature | Async | Defer |
|---|---|---|
| Execution Time | As soon as loaded | After HTML parsing |
| Order | Not guaranteed | Maintained order |
| Blocking | Non-blocking | Non-blocking |
Using type Attribute
Module Scripts
Best Practices
- Use external scripts for better maintainability
- Place scripts at the bottom or use defer
- Use async for independent scripts
- Minimize and optimize JavaScript files
- Avoid inline scripts in production
Common Mistakes
- Blocking page load with scripts in head
- Using async incorrectly for dependent scripts
- Mixing inline and external scripts unnecessarily
- Not optimizing script size
Conclusion
The script tag enables dynamic behavior in web pages. Proper usage of async, defer, and external scripts improves performance and maintainability.