What is the <script> tag?

<script> embeds or references JavaScript (or data blocks like JSON). By default a classic script blocks HTML parsing while it downloads and runs; defer, async and type="module" change that. It can contain inline code or load a file with src, and it appears in <head> or <body>.

Loading modes

  • Classic (no attributes): parsing stops, the script downloads and executes, then parsing resumes. Avoid in <head>.
  • defer: downloads in parallel, runs after the document is parsed, in order. Good default for app scripts.
  • async: downloads in parallel, runs as soon as it is ready (order not guaranteed). Good for independent scripts like analytics.
  • type="module": ES modules; deferred by default, strict mode, supports import/export, scoped variables. Add async to run as soon as ready.
  • nomodule: fallback for very old browsers that do not support modules (rarely needed today).

Other attributes

  • crossorigin, integrity (Subresource Integrity for CDN files), referrerpolicy, nonce (for Content Security Policy), fetchpriority, blocking="render".
  • type="importmap": map bare module specifiers to URLs.
  • type="application/ld+json": structured data for search engines.
  • type="speculationrules": prerender or prefetch likely next pages (Chromium).

Best practices

  • Prefer defer or modules for scripts in <head>.
  • Keep inline scripts small; move code to files that can be cached.
  • Avoid document.write.
  • Load third-party scripts with async and consider their performance and security cost.

Code example

html
1<!-- Import map: bare specifiers for ES modules -->
2<script type="importmap">
3 { "imports": { "confetti": "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm" } }
4</script>
5
6<!-- Module script: deferred by default, scoped, supports import -->
7<script type="module">
8 import confetti from "confetti";
9 document.querySelector("#party").addEventListener("click", () => confetti());
10</script>
11
12<!-- Structured data for search engines (not executed) -->
13<script type="application/ld+json">
14 { "@context": "https://schema.org", "@type": "Organization", "name": "DevQnA" }
15</script>
16
17<!-- Classic deferred script would look like: <script src="/app.js" defer></script> -->
18
19<button id="party">Celebrate 🎉</button>
20<p id="status">Status: <span>parsing…</span></p>
21<script>
22 // Inline classic script: runs immediately at this point in the document
23 document.querySelector("#status span").textContent = "inline script ran";
24</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app