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

后端 未结 4 1775
孤街浪徒
孤街浪徒 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:23

    By loading the script asynchronously, you are telling the browser that it can load that script independently of the other parts of the page. That means that the page may finish loading and may fire DOMContentLoaded BEFORE your script is loaded and before it registers for the event. If that happens, you will miss the event (it's already happened when you register for it).

    In some browsers, you can test the document to see if it's already loaded. I haven't checked all the browser compatibility, but in Firefox 3.6+ (MDN doc), you can check:

    if (document.readyState !== "loading")
    

    to see if the document is already loaded. If it is, just do your business. If it's not, then install your event listener.

    In fact, as a reference source and implementation idea, jQuery does this very same thing with it's .ready() method and it looks widely supported. jQuery has this code when .ready() is called that first checks to see if the document is already loaded. If so, it calls the ready function immediately rather than binding the event listener:

    // Catch cases where $(document).ready() is called after the
    // browser event has already occurred.
    if ( document.readyState === "complete" ) {
        // Handle it asynchronously to allow scripts the opportunity to delay ready
        return setTimeout( jQuery.ready, 1 );
    }
    

提交回复
热议问题