Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách kiểm tra document đã sẵn sàng (ready) trong JavaScript

Kiểm tra trạng thái tải trang với document.readyState

Thuộc tính document.readyState cho biết trạng thái tải tài liệu:

  • "loading" - Đang tải HTML, chưa parse xong.
  • "interactive" - HTML parse xong, DOM sẵn sàng, đang tải resource (CSS, images).
  • "complete" - Tải xong mọi thứ (HTML, CSS, JS, images, iframe...).

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document Ready State</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; color: blueviolet; font-family: monospace; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Kiểm tra Document Ready State</h1>
    <div class="result"></div>
    <button class="btn-demo">KIỂM TRA</button>
    <h3>Nhấn nút để xem trạng thái tài liệu</h3>

    <script>
        const resEle = document.querySelector(".result");
        const btn = document.querySelector(".btn-demo");

        // Trạng thái lúc script chạy (thường là "interactive")
        resEle.textContent = "Trạng thái ban đầu: " + document.readyState + "\n\n";

        btn.addEventListener("click", () => {
            if (document.readyState === "complete") {
                resEle.textContent = "Trang đã tải HOÀN TOÀN xong (complete)";
            } else {
                resEle.textContent = "Trang ĐANG tải: " + document.readyState;
            }
        });
    </script>
</body>
</html>

Các cách phổ biến để chạy code khi DOM ready

1. DOMContentLoaded (Khuyến nghị - không chờ CSS/images)

document.addEventListener('DOMContentLoaded', () => {
    // DOM đã parse xong, sẵn sàng thao tác
    console.log('DOM ready!');
});

2. window.onload (Chờ tất cả resource)

window.addEventListener('load', () => {
    // Toàn bộ trang đã load xong (ảnh, CSS, iframe...)
    console.log('Page fully loaded!');
});

3. Script ở cuối body (Cách cổ điển)

<body>
    <!-- Nội dung HTML -->
    <script>
        // DOM đã sẵn sàng vì script ở cuối
        console.log('DOM ready!');
    </script>
</body>

4. defer attribute (HTML5)

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

5. async attribute

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

So sánh

Cách Chờ DOM? Chờ Resource? Thứ tự Dùng cho
DOMContentLoaded✓✗Sau parse HTMLKhởi tạo UI, gán event
window.onload✓✓Cuối cùngĐo kích thước ảnh, analytics
Script cuối body✓✗Theo thứ tự HTMLSimple pages
defer✓✗Trước DOMContentLoadedExternal scripts
async✗✗Không đảm bảoIndependent scripts (ads, analytics)

Best Practice hiện đại

<!-- Head: critical CSS, preload -->
<script type="module" src="main.js" defer></script>

<!-- main.js -->
// type="module" tự động defer
// Code chạy khi DOM ready
document.addEventListener('DOMContentLoaded', initApp);

function initApp() { ... }