How to know if window “load” event was fired already

后端 未结 7 2089
独厮守ぢ
独厮守ぢ 2020-12-05 12:27

I\'m writing a Javascript script. This script will probably be loaded asynchronously (AMD format).

In this script, I\'d like to do nothing important until the

7条回答
  •  一整个雨季
    2020-12-05 13:05

    Here is my answer:

    fiddle

    window.addEventListener("load", function () {
        window.loaded = true;
    });
    
    function logLoaded() {
        console.log("loaded");
    }
    
    (function listen () {
        if (window.loaded) {
            logLoaded();
        } else {
            console.log("notLoaded");
            window.setTimeout(listen, 50);
        }
    })();
    

    You can read about addEventListener() and its compatibility (it is new to the ECMAScript 5 spec) here. It is the new "preferred" way to do things going forward.

    You can read about Immediately Invoked Function Expressions (IIFE) (alternately, self-invoked anonymous functions or immediately invoked anonymous functions) here.

    EDIT: Here is a good answer already on StackOverflow:

    How to check if DOM is ready without a framework?

    If you specifically want to know if the DOM load event has fired, set a global variable in a DOM 'load' event handler and then check for its existence when your new code loads.

    // in 'load' event handler
    window.domLoadEventFired = true;
    
    // in code you are loading asynchronously
    if (typeof window.domLoadEventFired !== undefined) {
        // ...
    }
    

提交回复
热议问题