Keep JavaScript Module Scope Separate from iframe Documents

Setting type="module" on the parent page does not turn scripts inside an iframe into modules. An iframe loads a separate document with its own scripts, global object and module graph. Declare module scripts in each document that needs them.

Last updated: November 24, 2026.

<!-- launcher.html -->
<iframe id="game" src="/games/chess/index.html" title="Chess game"></iframe>
<script type="module" src="/js/launcher.js"></script>

<!-- /games/chess/index.html: a separate document -->
<canvas id="board"></canvas>
<script type="module" src="./game.js"></script>

The parent module can create, remove or navigate the iframe element, but the child document still loads and executes its own scripts. Do not add type="module" to a legacy child script unless that script is actually written as a module.

Treat the iframe as an independent application

MDN describes an iframe as a complete nested browsing context with its own document. The parent’s imports, variables and functions are not automatically visible inside it. Likewise, a function declared by the child is not added to the parent module’s scope.

Module scripts have their own scope, use strict mode automatically and are deferred by default. Follow the JavaScript modules guide: export values from files that own them and import those values only inside the same document’s module graph. If a child page still uses classic global scripts, leave them classic until its dependencies and inline handlers have been migrated together.

Communicate across the frame boundary deliberately

For same-origin content, the parent may access iframe.contentWindow or contentDocument after the frame loads. Cross-origin access is restricted by the same-origin policy. Use window.postMessage() when separate documents need to exchange small messages, and validate both event.origin and event.source.

When an embedded game reports “is not a function,” inspect the console for that frame, not only the top-level page. Confirm the child script URL, response type, import paths and whether the referenced function is exported or intentionally global. The parent becoming a module is not itself a reason for an iframe to stop loading.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov