HTML · Chapter 25 of 45

HTML and the JavaScript Tag

The <script> tag embeds or links JavaScript code within an HTML page, either inline between the tags or via the src attribute pointing to an external file.

Scripts are commonly placed at the end of <body>, or loaded with the defer attribute in <head>, so they don't block the page from rendering while downloading.

Syntax
<script src="file.js" defer></script>

Inline vs external scripts

Inline scripts are written directly between <script> tags. External scripts use src="file.js" and are cacheable and reusable across pages.

Loading behavior

The defer attribute delays script execution until after the HTML is parsed, without blocking rendering, and is recommended for most scripts placed in the head.

Example 1 (html)
<script>
  alert('Hello from JavaScript!');
</script>
Output
(shows an alert box: Hello from JavaScript!)

Inline JavaScript runs immediately when the browser reaches this tag.

Example 2 (html)
<head>
  <script src="app.js" defer></script>
</head>
Output
(app.js runs after HTML parsing completes)

defer lets the browser download the script early but run it after parsing.

Key points

  • <script> embeds or links JavaScript code.
  • src attribute loads an external .js file.
  • defer runs scripts after HTML parsing without blocking rendering.
  • Scripts placed at the end of <body> also avoid blocking render.
💡 Note: The older <noscript> tag shows fallback content for users with JavaScript disabled.

📝 Quick Quiz

1. Which tag embeds JavaScript in HTML?

2. What does the defer attribute do?

3. Which attribute loads an external JS file?