Async-loaded scripts with DOMContentLoaded or load event handlers not being called?

后端 未结 4 1780
孤街浪徒
孤街浪徒 2020-12-04 17:48

I\'ve got a script with a DOMContentLoaded event handler—

document.addEventListener(\'DOMContentLoaded\', function() {
    console.log(\'Hi\');
         


        
4条回答
  •  悲哀的现实
    2020-12-04 18:38

    One way around this is to use the load event on the window object.

    This will happen later than DOMContentLoaded, but at least you don't have to worry about missing the event.

    window.addEventListener("load", function () {
       console.log('window loaded');
    });
    

    If you really need to catch DOMContentLoaded event you can do use Promise object. Promise will get resolved even if it happened earlier:

    HTMLDocument.prototype.ready = new Promise(function (resolve) {
    if (document.readyState != "loading")
        return resolve();
    else
        document.addEventListener("DOMContentLoaded", function () {
            return resolve();
        });
    });
    
    document.ready.then(function () {
        console.log("document ready");
    });
    

提交回复
热议问题