Reference · Intermediate

The script element

Use script to load or embed executable JavaScript or data, with deliberate loading order, security policy, and no-script behavior.

Published
Last checked

Definition

script embeds data or executable code, most commonly JavaScript. A classic external script, a JavaScript module, and a JSON data block have different loading and execution contracts. Declare only the contract the document needs.

Module syntax

<script type="module" src="/assets/app.js"></script>

Modules are deferred by default, use strict mode, and support imports. A classic script without async or defer can block parsing while it downloads and runs.

Loading choices

Use defer for ordered classic scripts that may run after parsing. Use async for independent scripts whose execution order does not matter. Modules have their own dependency graph. Do not add both attributes by habit; decide whether the script depends on document readiness, another script, or an early execution point.

Security and resilience

External scripts execute with the page's authority. Minimize third parties, restrict sources with Content Security Policy, and use integrity metadata where the hosting arrangement supports immutable cross-origin assets. Keep the main content and navigation usable if a script is slow, blocked, or throws before initialization.

Common failures

  • A render-blocking script sits in the head without a demonstrated need.
  • async scripts depend on one another and race in production.
  • A third-party script collects data not disclosed by the privacy policy.
  • A module path works locally but fails under the deployed base path or MIME type.

Verification checklist

Disable JavaScript and confirm the baseline remains truthful. Throttle the network, block each third-party host, and force one script to fail. Inspect the production waterfall, content types, cache headers, CSP, console, and runtime logs. Confirm no secret enters the public bundle and no script reports success before the authoritative request succeeds.

Repeat the production check with a fresh cache and after consent choices where applicable. A script that is absent on first load may appear after interaction, and a cached response can hide a broken module path or deployment-specific content type.