자바스크립트 로딩 상태 확인

When building a website or web application, it’s common to have JavaScript code that needs to be executed once the page has finished loading. To ensure that your JavaScript code runs at the right time, you need to be able to check the loading status of the page.

In JavaScript, there are multiple events and methods that can be used to determine the loading state of the page. Let’s explore a few options:

1. “DOMContentLoaded” Event

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed. This event is a good indicator that the page’s DOM (Document Object Model) is ready for manipulation.

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code here
});

2. “load” Event

The load event is fired when the whole page (including all external resources like images, stylesheets, and scripts) has finished loading. This event is suitable for scenarios where you need to interact with elements that rely on external resources.

window.addEventListener("load", function(event) {
    // Your code here
});

3. “readystatechange” Event

The readystatechange event is fired when the ready state of the document changes. The different ready states are loading, interactive, and complete. You can use this event to perform actions at specific stages of the loading process.

document.addEventListener("readystatechange", function(event) {
    if (document.readyState === "interactive") {
        // Your code here
    }
});

These are just a few examples of how you can check the loading status of a JavaScript file on a web page. Depending on your specific requirements, you can choose the event or method that best suits your needs.

By understanding and utilizing these loading state checks, you can ensure that your JavaScript code runs at the appropriate time, avoiding any potential issues with manipulating elements that haven’t finished loading yet.

Remember to always test your code thoroughly to ensure it behaves as expected in various scenarios. Happy coding!