0Pricing
Web Performance Optimization & Lighthouse · 课时

高效的脚本加载策略

掌握异步加载 JavaScript、延迟加载非关键脚本以及有效使用模块模式的技术。

高效的脚本加载策略 是 CoddyKit 上的免费 Web Performance Optimization & Lighthouse 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Performance Optimization & Lighthouse 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Fast Scripts, Fast Pages

JavaScript powers interactive web experiences. But if not loaded efficiently, it can significantly slow down your website.

A slow loading script can block your page from rendering, making users wait longer to see and interact with content.

In this lesson, we'll explore strategies to load scripts smartly, ensuring your users get a smooth, fast experience.

Scripts Block Rendering

By default, when a browser encounters a <script> tag in your HTML, it pauses parsing the HTML document.

It fetches, parses, and executes the script immediately. Only after the script finishes can HTML parsing resume.

This can be a major bottleneck, especially for large scripts. Try running this simple script to see how it can simulate a blocking operation:

console.log("HTML parsing paused (simulated).");
// Simulate a computationally heavy task
let sum = 0;
for (let i = 0; i < 100000000; i++) {
  sum += i;
}
console.log("Blocking script finished. Sum:", sum);
console.log("HTML parsing resumes (simulated).");

`async`: Load in Parallel

The async attribute tells the browser to download the script in parallel with parsing the HTML document.

  • Non-blocking: HTML parsing continues while the script downloads.
  • Execute immediately: The script executes as soon as it's downloaded, without waiting for the HTML to finish parsing.
  • Order not guaranteed: Scripts with async might execute in any order, potentially out of the order they appear in the HTML.

Use async for independent scripts like analytics or ads that don't rely on other scripts or the full DOM.

`async` in Action

Imagine this script is loaded with <script async src="my-async-script.js"></script>.

It downloads in the background, and once ready, runs right away. Other page content can continue loading.

Notice how "Page content continues..." might appear before "Async script finished" in a real browser scenario, as the script doesn't block.

console.log("Async script started downloading.");
// Simulate fetching data or setting up a listener
setTimeout(() => {
  console.log("Async script finished execution.");
}, 50); // Small delay to simulate download + execution
console.log("Page content continues to load in parallel.");

`defer`: Execute After HTML

The defer attribute also makes scripts non-blocking, but with a key difference in execution time.

  • Non-blocking: Like async, the script downloads in parallel with HTML parsing.
  • Execute after HTML: The script executes only after the HTML document has been completely parsed.
  • Order guaranteed: Scripts with defer execute in the exact order they appear in the HTML.

defer is ideal for scripts that depend on the full DOM, like interactive elements or form validations, but don't need to block initial rendering.

`defer` in Action

This script, loaded with <script defer src="my-defer-script.js"></script>, would wait for all HTML to be processed before running.

It's perfect for scripts that need to interact with elements on the page without blocking the user from seeing content first.

console.log("Defer script started downloading.");
// Simulate DOM manipulation or event setup
setTimeout(() => {
  // In a real browser, document.getElementById would now work.
  console.log("Defer script finished execution after HTML parsed.");
}, 50); // Small delay
console.log("HTML parsing completed (simulated) before defer script runs.");

Pick Your Strategy

Understanding the differences between async and defer is crucial for optimal performance:

  • async: For independent scripts that don't care about DOM readiness or other script order (e.g., analytics, third-party widgets).
  • defer: For scripts that rely on the DOM being fully parsed, or depend on the execution order of other deferred scripts (e.g., UI interactivity, custom validations).
  • No attribute: Blocks rendering. Only use for critical scripts that must run before anything else.

ES Modules: Modern Scripting

ES Modules (ECMAScript Modules) provide a standardized system for organizing JavaScript code into separate files that can import and export functionalities.

When you use <script type="module">, the browser treats your script differently:

  • Deferred by default: Modules are automatically deferred, meaning they don't block HTML parsing.
  • Strict Mode: Modules run in strict mode by default.
  • Scoped: Variables and functions declared at the top-level of a module are scoped to that module, not global.

How Modules Load

ES Modules use import to bring in functionality from other files and export to make functionality available.

The browser handles module loading efficiently, fetching dependencies in parallel and executing them in the correct order, after the HTML is parsed.

Here's a look at basic module syntax:

// Example: myUtils.js
export const PI = 3.14159;
export function multiply(a, b) {
  return a * b;
}

// Example: main.js (loaded with <script type="module">)
import { PI, multiply } from './myUtils.js';

console.log("Module imported successfully.");
console.log("PI value:", PI);
console.log("5 * 10 =", multiply(5, 10));

Script Loading Choices

You're building a website and need to load several JavaScript files. Which of the following statements about efficient script loading are TRUE?

Recap: Mastered Loading

Great job! You've learned how to load JavaScript efficiently:

  • Default scripts block parsing, slowing down your page.
  • The async attribute allows scripts to download in parallel and execute immediately, ideal for independent scripts.
  • The defer attribute also downloads in parallel but waits until the HTML is fully parsed before executing, maintaining order.
  • ES Modules (<script type="module">) offer a modern, structured way to organize code, behaving like deferred scripts by default.

By applying these strategies, you can significantly improve your website's perceived and actual loading performance!

常见问题解答

「高效的脚本加载策略」课时是免费的吗?

是的 — 「高效的脚本加载策略」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Performance Optimization & Lighthouse 课程的其余内容,请升级到 CoddyKit PRO。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。

「高效的脚本加载策略」这节课中我会学到什么?

掌握异步加载 JavaScript、延迟加载非关键脚本以及有效使用模块模式的技术。 你通过在浏览器中直接运行的动手代码来练习 Web Performance Optimization & Lighthouse,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web Performance Optimization & Lighthouse 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web Performance Optimization & Lighthouse 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「高效的脚本加载策略」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web Performance Optimization & Lighthouse 课中编写并运行代码吗?

能。每节 Web Performance Optimization & Lighthouse 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 缩减 JavaScript 负载
  2. 高效的脚本加载策略
  3. Web Workers 与主线程卸载
  4. 代码拆分与延迟加载
← 返回 Web Performance Optimization & Lighthouse