script element

Use script to run JavaScript in an HTML document. Choose loading attributes based on whether execution order and document readiness matter.

What you will learn

Basic usage

Use src to load an external file, or place a small script between the opening and closing tags. A script with src should not also contain inline code.

External and inline scripts

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

<script>
  console.log('A small inline script');
</script>

Choose a loading mode

defer
Downloads while HTML is parsed, then runs after parsing in document order. This is a good default for scripts that use the page's elements.
async
Runs as soon as its download finishes. Use it for independent scripts such as analytics where order does not matter.
type="module"
Loads an ES module with import and export. Modules are deferred by default and have their own scope.

A module entry point

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

// main.js
import { add } from './math.js';
console.log(add(2, 3));

Execution and security tips

Related pages