html
/

HTML Script: Adding JavaScript to Web Pages

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

HTML Script: Adding JavaScript to Web Pages

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

HTMLRead-only
1
<script>
  alert('Hello World');
</script>

External Script

HTMLRead-only
1
<script src="script.js"></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.

HTMLRead-only
1
<body>
  <h1>Hello</h1>
  <script src="script.js"></script>
</body>

Async Attribute

The async attribute loads the script asynchronously without blocking HTML parsing.

HTMLRead-only
1
<script src="script.js" async></script>

Defer Attribute

The defer attribute ensures the script executes after the HTML document is fully parsed.

HTMLRead-only
1
<script src="script.js" defer></script>

Async vs Defer

FeatureAsyncDefer
Execution TimeAs soon as loadedAfter HTML parsing
OrderNot guaranteedMaintained order
BlockingNon-blockingNon-blocking

Using type Attribute

HTMLRead-only
1
<script type="text/javascript">
  console.log('Hello');
</script>

Module Scripts

HTMLRead-only
1
<script type="module" src="app.js"></script>

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.

Try it yourself

<button onclick="alert('Clicked!')">Click Me</button>

Test Your Knowledge

Q1
of 3

Which tag is used to add JavaScript?

A
<js>
B
<script>
C
<code>
D
<style>
Q2
of 3

Which attribute loads script after parsing?

A
async
B
defer
C
load
D
run
Q3
of 3

Which is better for independent scripts?

A
defer
B
async
C
inline
D
type

Frequently Asked Questions

What does the script tag do?

It is used to add JavaScript to HTML pages.

What is the difference between async and defer?

Async executes immediately after loading, while defer waits until HTML parsing is complete.

Where should scripts be placed?

At the bottom of the body or using defer for better performance.

Previous

html dialog

Next

html noscript

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.