nomodule必须与type="module"成对使用,单独使用会导致新旧浏览器均白屏;现代浏览器跳过nomodule脚本,旧浏览器如ie11则静默忽略整行标签,故需双标签互斥加载且legacy脚本须es5兼容并含polyfill。

nomodule 必须和 type="module" 成对出现,单独用会白屏
只写 <script nomodule src="legacy.js"></script> 是最常见错误:现代浏览器跳过它(不发请求),旧浏览器如 IE11 会静默忽略整行标签(不执行也不报错),结果新旧用户都无 JS 可用。typeof module 在 IE11 返回 "undefined",但 legacy.js 也没运行,基本就能确认是单写 nomodule 导致的丢弃。
真正起作用的是组合:<script type="module" src="app.mjs"></script> 和 <script nomodule src="legacy-bundle.js"></script>。两者互斥——现代浏览器走左边,旧浏览器走右边,中间没有交集。
- 顺序建议模块优先,但 DOM 顺序不影响逻辑
- Chrome DevTools Network 面板搜
legacy-bundle.js,它不该出现(说明被现代浏览器跳过) - IE11 控制台执行
console.log(typeof module)应为"undefined",且legacy-bundle.js的代码应正常运行
legacy-bundle.js 必须是真·ES5 + 手动 polyfill
nomodule 只管“要不要加载”,不管“能不能跑”。哪怕脚本进了 IE11,以下任一情况都会立刻崩溃:
- 语法层面:含
const、let、=>、${}、class→ 直接SyntaxError - API 层面:调用
fetch()、Promise、Array.from()、Object.assign()→ReferenceError或静默失败 - DOM 层面:用
element.classList.add()(IE9–)、querySelector()(IE7–)、addEventListener()(IE8–)→ 报错或无响应
构建时必须显式设 targets: { ie: "11" },不能依赖 Babel 默认 preset;core-js/stable 需手动引入,且 polyfill 必须在所有业务代码之前执行;输出格式只能是 IIFE 或 UMD,严禁含 import/export,禁用 dynamic import()。
Safari 10.1 的双执行陷阱要 runtime 规避
Safari 10.1(macOS 10.12.4 / iOS 10.3)识别 type="module",却错误地也执行 nomodule 脚本,导致 UI 初始化两次、事件重复绑定、数据请求翻倍。
最稳妥的缓解方式是加一层运行时检测,只在“半吊子”浏览器中注入 fallback:
if (!('noModule' in document.createElement('script')) && !('onbeforeload' in document.createElement('script'))) {
const s = document.createElement('script');
s.src = 'legacy-bundle.js';
document.head.appendChild(s);
}
这个判断能精准捕获 Safari 10.1 这类“伪模块支持者”,避免双执行,又不影响其他环境。
nomodule 脚本默认同步阻塞,旧浏览器里得显式 defer
type="module" 脚本默认是 defer 行为(按文档顺序执行,不阻塞 HTML 解析),而 nomodule 脚本在旧浏览器中表现和普通 <script></script> 一样:若无 defer 或 async,会同步阻塞解析。
为保持行为一致,推荐显式控制:
- 现代路径:
<script type="module" src="app.mjs"></script>(已 defer) - 旧路径:
<script nomodule defer src="legacy-bundle.js"></script>(显式加defer,避免阻塞)
否则 legacy-bundle.js 可能在 DOM 尚未就绪时就运行,导致 document.getElementById 返回 null 等问题。
容易被忽略的是:旧浏览器对 defer 支持有限(IE9+ 才可靠),所以压缩 + 内联关键初始化逻辑仍是必要兜底手段。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











