HTML / Element

How to Use the script Element

The HTML <script> element adds JavaScript or another script-supported data block to a document. Choosing the loading mode helps you control page parsing and execution order.

The answer first

For an external script that should wait until HTML has been parsed and then run in document order, start by considering defer.

Use async for independent work, and use type="module" when your code is organized with import and export.

Minimal examples

Use src to load an external file. Do not put executable code in the same element and expect it to run alongside the external source.

<script src="app.js" defer></script>

You can also place a small script directly in the document.

<script>
  console.log('Starting the page');
</script>

defer, async, and module

FormExecution behaviorGood fit
deferFetches while HTML is parsed, then runs in document order after parsingRegular external scripts that use the DOM
asyncRuns when its download is ready; execution order is not guaranteedIndependent work such as analytics
type="module"Loads a module and, by default, evaluates it after HTML parsingCode organized with import and export

Do not add both modes without a reason. First decide whether the script depends on other scripts or on the document being parsed.

A module example

Modules have their own scope and explicitly import the functions they use.

<script type="module" src="./main.js"></script>

// main.js
import { add } from './math.js';

console.log(add(2, 3));

Common mistakes

  • Using async when several scripts must run in a specific order
  • Running a DOM-dependent script synchronously before the required elements have been parsed
  • Assuming type="text/javascript" is required. For ordinary JavaScript, type can usually be omitted
  • Using JavaScript for every navigation or display task instead of choosing the appropriate HTML element

Safer script loading

Load external scripts over HTTPS from sources you trust. Do not insert user input into HTML as executable script, and consider a Content Security Policy (CSP) when your site needs an additional policy boundary.

Check it in Atlas

For script variants, processing order, Fetch and CSP boundaries, and known incomplete areas, see the script element in Yugien Atlas.