Codectionary / Developer documentation / HTML

<script>

The <script> element embeds or references executable JavaScript code within an HTML document. It can contain inline code directly between its tags, or load an external file via the src attribute. Where scripts are placed and how they load (defer, async, or neither) significantly affects page load performance and execution order.

Syntax

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

Examples

External Script

Loading JavaScript from a separate file.

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

Inline Script

Writing JavaScript directly within the HTML document.

<script>
  console.log("Page loaded");
  document.addEventListener("DOMContentLoaded", () => {
    console.log("DOM ready");
  });
</script>

Deferred and Module Scripts

Controlling load timing and using ES modules.

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

Attributes

  • src (URL): Path to an external JavaScript file
  • defer (boolean): Delays execution until after the document is parsed, preserving order
  • async (boolean): Downloads the script in parallel and executes as soon as it is ready, out of order
  • type (module | text/javascript): Specifies the scripting language or module type

Best practices

  • Place scripts before the closing </body> tag, or use defer, so they do not block HTML rendering
  • Use defer for scripts that need to run in order and depend on the full DOM being parsed
  • Use async only for independent scripts where execution order does not matter, like analytics
  • Prefer external scripts with src over large inline scripts for better caching and readability

At a glance

Purpose
Structure and meaning for web content
File extension
.html · .htm
Runs in
Web browsers
Usually used with
CSS and JavaScript

Specifications & further reading

Related HTML documentation