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

后端 未结 7 2063
独厮守ぢ
独厮守ぢ 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:03

    Browser navigation performance loadEventEnd metric can be used to determinate if load event was triggered:

    let navData = window.performance.getEntriesByType("navigation");
    if (navData.length > 0 && navData[0].loadEventEnd > 0)
    {
        console.log('Document is loaded');
    } else {
        console.log('Document is not loaded');
    }
    
    0 讨论(0)
  • 2020-12-05 13:04

    Based on @CTS_AE's approach, I have put together a solution for envrionments where:

    • window.addEventListener('load', activateMyFunction); and
    • window.addEventListener('DOMContentLoaded', activateMyFunction);

    don't work.

    It requires a single character substitution (eg. from

    window.addEventListener('load', activateMyFunction);
    

    to

    window_addEventListener('load', activateMyFunction);)
    

    The function window_addEventListener() looks like this:

    const window_addEventListener = (eventName, callback, useCapture = false) => {
    
      if ((document.readyState === 'interactive') || (document.readyState === 'complete'))   {
    
        callback();
      }
    }
    
    0 讨论(0)
  • 2020-12-05 13:05

    Quick Answer

    To quickly answer the question's title:

    document.readyState === 'complete'
    

    Deeper Example

    Below is a nice helper if you want to call code upon a window load, while still handling the case where the window may have already loaded by the time your code runs.

    function winLoad(callback) {
      if (document.readyState === 'complete') {
        callback();
      } else {
        window.addEventListener("load", callback);
      }
    }
    
    winLoad(function() {
      console.log('Window is loaded');
    });

    Note: code snippets on here actually don't run in the same window context so document.readyState === 'complete' actually evaluates to false when you run this. If you put the same into your console right now for this window it should evaluate as true.

    See also: What is the non-jQuery equivalent of '$(document).ready()'?

    0 讨论(0)
  • 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) {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-05 13:07

    If you don't want to use jQuery, the logic it uses is:

    if( !document.body )
        setTimeout( checkAgain, 1 );
    

    So between the windows loaded event and checking if the body property of the document is available, you can check if the DOM is ready

    0 讨论(0)
  • 2020-12-05 13:20

    The easiest solution might be checking for document.readyState == 'complete', see http://www.w3schools.com/jsref/prop_doc_readystate.asp

    0 讨论(0)
提交回复
热议问题