Skip to main content

The <script> Element

As defined in the HTML Living Standard, the <script> element allows authors to include dynamic scripts and data blocks in their documents. The element either contains scripting statements or points to an external script file using the src attribute.

<script src="app.js"></script>
<script>
  console.log("Internal script execution.");
</script>

The <script> tag can be placed in either the <head> or the <body>, depending on when you want the logic to execute.

View HTML Living Standard: The script element

Performance & Accessibility: Async vs. Defer

The way a script is loaded can significantly impact the perceived performance and accessibility of a page.

<script src="analytics.js" async></script> <script src="ui-logic.js" defer></script>

WCAG and Script-Generated Content

If your script dynamically generates content or changes the state of the UI, you must follow specific accessibility rules.

WCAG Requirement: Name, Role, Value

Success Criterion 4.1.2 (Level A): For all user interface components, the name and role can be programmatically determined...

When using scripts to create custom widgets (like a custom dropdown or a carousel), the script must manage the ARIA roles and states manually. For example, if a script toggles a menu, it should update aria-expanded="true/false" so screen reader users are notified of the change.

Understand SC 4.1.2: Name, Role, Value

Security & Integrity

Modern standards provide attributes to ensure that scripts are loaded securely and haven't been tampered with.

<script src="https://cdn.example.com/lib.js" xintegrity="sha384-..." crossorigin="anonymous"> </script>

Best Practices

A11y Tip: Reducing Motion

If your script handles animations, use the window.matchMedia('(prefers-reduced-motion: reduce)') query to detect if a user has requested minimal movement, satisfying WCAG SC 2.3.3 (Animation from Interactions).