Skip to content

异步 Script Execution 顺序

快速摘要

你的异步 scripts 执行 as soon as 它们 download, potentially out 的顺序 — 如果 script B depends on script , B 可能运行之前 .

为什么发生

  • Using 异步 on scripts 那个 depend on 每个 other

  • Mixing 异步 and defer 不正确地

  • Assuming scripts 执行 in 顺序它们 appear in HTML

最小示例

✗ 错误代码
<!-- async scripts execute in download order, not DOM order -->
<script src="library.js" async></script>
<script src="app.js" async></script>
<!-- If app.js loads first, it fails because library.js is not ready -->
✓ 修复代码
<!-- defer scripts execute in DOM order after parsing -->
<script src="library.js" defer></script>
<script src="app.js" defer></script>
<!-- app.js always runs after library.js -->

异步执行 scripts as soon as 它们 download, in 任何顺序. defer downloads in parallel 但执行 in 顺序, guaranteeing 库.js 运行之前 app.js.

如何诊断

  • 检查哪个 scripts 有异步 attribute

  • Look for 错误如 'X 是不 定义' 那个 indicate dependency issues

  • Use Network tab 到 see download and execution 顺序

如何修复

  • Use defer 相反的 异步 for scripts 那个 depend on 每个 other — defer preserves 顺序

  • Bundle dependent scripts 到单个 file

  • Use 动态导入() for explicit dependency management

如何预防

  • Use defer for 非-关键 scripts 那个需要有序 execution

  • Use 异步仅 for independent scripts (analytics, tracking 像素)

  • Bundle scripts 使用构建 tool 到 manage dependencies

相关资源

相关术语

相关课程

← 返回语言