Blogs
Defer - Async - Inline, cách browser thực thi JavaScript

Defer - Async - Inline, cách browser thực thi JavaScript

Giải thích sự khác nhau giữa defer, async, và inline trong việc thực thi JavaScript và cách chúng ảnh hưởng đến hiệu suất trang web.

Cách browser thực thi JavaScript: Hiểu rõ defer, async, và inline

Khi bạn nhúng JavaScript vào HTML, việc browser thực thi script ở đâu và khi nào sẽ ảnh hưởng trực tiếp đến hiệu suất tải trang, trải nghiệm người dùng, và thứ tự thực thi code.

3 phương pháp phổ biến để nhúng script là:

  • Inline script
  • Script với defer
  • Script với async

Hiểu rõ sự khác nhau giữa chúng là kỹ năng quan trọng của một frontend developer.


1. Inline script là gì?

Inline script là đoạn JavaScript được viết trực tiếp trong file HTML, thường nằm trong thẻ <script> không có thuộc tính src.

Ví dụ:

<script> console.log("Hello from inline script"); </script>

Đặc điểm:

  • Thực thi ngay lập tức khi trình duyệt parser đến đoạn này.
  • Chặn quá trình render HTML tiếp theo cho đến khi script thực thi xong.
  • Không thể cache vì nằm trực tiếp trong HTML.

Khi nào nên dùng?

  • Đoạn script nhỏ, chạy rất nhanh (dưới 1–2ms).
  • Các biến cấu hình cần thiết sớm (như window.__ENV__ = {...}).
  • Tracking code bắt buộc chạy đầu tiên (như Google Tag Manager snippet).

2. Script có thuộc tính defer

Ví dụ:

<script defer src="/main.js"></script>

Đặc điểm:

  • Tải song song với quá trình phân tích HTML.
  • Chỉ thực thi sau khi toàn bộ HTML đã được parser xong.
  • Giữ thứ tự giữa các script có defer.

Trình duyệt sẽ:

  1. Bắt đầu phân tích HTML.
  2. Gặp <script defer>, tải file JS song song.
  3. Tiếp tục phân tích HTML.
  4. Sau khi HTML parser xong → thực thi các script defer theo thứ tự.

Ưu điểm lớn của deferkhông chặn rendergiữ được thứ tự.


3. Script có thuộc tính async

Ví dụ:

<script async src="/analytics.js"></script>

Đặc điểm:

  • Tải song song với HTML, thực thi ngay khi tải xong, không chờ HTML parser hoàn tất.
  • Không đảm bảo thứ tự giữa các script async.

Tức là:

  • Nếu analytics.js tải xong trước ads.js, nó sẽ chạy trước, bất kể thứ tự bạn khai báo.
  • Trong lúc chạy async, việc parser HTML sẽ tạm dừng → có thể gây layout jank nhẹ.

Sử dụng async khi script độc lập, không phụ thuộc vào nội dung DOM hoặc các script khác.


So sánh inline, defer, async

Thuộc tínhTải song songChặn HTML parserThực thi sau HTML parserGiữ thứ tự
Inline
<script defer>
<script async>❌ (tạm)

Khi nào dùng cái nào?

Tình huốngCách dùng đề xuất
Script phụ thuộc vào DOM (manipulate DOM)defer
Script tracking, analytics, ads độc lậpasync
Biến cấu hình nhỏ cần sớminline
Thư viện JS lớn như React, Vuedefer

Bonus: Dùng type="module" có tác dụng gì?

Từ HTML5+, bạn có thể dùng:

<script type="module" src="/app.js"></script>

Tự động ngầm hiểu là defer, nên:

  • Không chặn HTML parser.
  • Được thực thi sau khi HTML đã parser xong.
  • Hỗ trợ import/export.

type="module" thích hợp khi bạn dùng ES Modules và bundler hiện đại như Vite, Webpack, hoặc Next.js.


Kết luận

Hiểu được defer, async, và inline sẽ giúp bạn:

  • Kiểm soát được trình tự thực thi script
  • Tối ưu hiệu suất tải trang
  • Tránh bug do script chạy trước khi DOM sẵn sàng

Hãy chọn cách nhúng script phù hợp với mục đích sử dụng và đặc điểm của từng loại để mang lại trải nghiệm tốt nhất cho người dùng.

Defer - Async - Inline, how Browsers Execute JavaScript

An explanation of the differences between defer, async, and inline in JavaScript execution and how they impact web performance.

How Browsers Execute JavaScript: Understanding defer, async, and inline

When you embed JavaScript in HTML, the location and timing of execution will directly affect the page load performance, user experience, and execution order of the code.

Three common methods to include JavaScript are:

  • Inline script
  • Script with defer
  • Script with async

Understanding the differences between these methods is a key skill for any frontend developer.


1. What is Inline Script?

An inline script is a JavaScript code that is written directly within the HTML file, typically inside a <script> tag without the src attribute.

Example:

<script> console.log("Hello from inline script"); </script>

Characteristics:

  • Executes immediately when the browser parser encounters it.
  • Blocks further HTML rendering until the script finishes executing.
  • Cannot be cached, as it's directly in the HTML.

When should you use it?

  • For small, quick scripts (under 1-2ms).
  • For configuration variables that need to be available early (like window.__ENV__ = {...}).
  • For tracking scripts that must execute first (like Google Tag Manager snippet).

2. What is a defer Script?

Example:

<script defer src="/main.js"></script>

Characteristics:

  • Loads in parallel with the HTML parsing.
  • Executes after the HTML has been fully parsed.
  • Maintains the order of deferred scripts.

In this case, the browser will:

  1. Start parsing the HTML.
  2. Encounter the <script defer> tag, loading the JS file in parallel.
  3. Continue parsing the rest of the HTML.
  4. After the HTML parsing is complete, execute the deferred scripts in the order they were encountered.

The main advantage of defer is that it does not block rendering and preserves execution order.


3. What is an async Script?

Example:

<script async src="/analytics.js"></script>

Characteristics:

  • Loads in parallel with HTML, executes as soon as it's loaded, does not wait for the HTML parser to finish.
  • Does not maintain order between async scripts.

In this case:

  • If analytics.js finishes loading before ads.js, it will execute first, regardless of the order you declared them in.
  • While an async script is executing, the HTML parsing pauses, which may cause layout jank.

Use async for independent scripts that don’t rely on the DOM or other scripts.


Comparison of inline, defer, and async

AttributeLoads in ParallelBlocks HTML ParsingExecutes After HTML ParsingMaintains Order
Inline
<script defer>
<script async>❌ (temporarily)

When Should You Use Which?

ScenarioRecommended Usage
Scripts that depend on DOM (manipulate DOM)defer
Independent tracking, analytics, ads scriptsasync
Small configuration variables that need to run earlyinline
Large JavaScript libraries like React, Vuedefer

Bonus: What Does type="module" Do?

Starting from HTML5+, you can use:

<script type="module" src="/app.js"></script>

This implicitly means defer, so:

  • Does not block HTML parsing.
  • Executes after HTML parsing completes.
  • Supports import/export.

type="module" is ideal when using ES Modules and modern bundlers like Vite, Webpack, or Next.js.


Conclusion

Understanding defer, async, and inline allows you to:

  • Control the order of script execution.
  • Optimize page load performance.
  • Avoid bugs caused by scripts executing before the DOM is ready.

Choose the appropriate method for embedding scripts based on the use case to ensure the best possible user experience.

Tags

Buy Me A Coffee
    JavaScriptPerformance