Code inside DOMContentLoaded event not working

前端 未结 7 1593
一向
一向 2020-12-04 20:10

I have used




  


  
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 20:28

    It's most likely because the DOMContentLoaded event was already fired at this point. The best practice in general is to check for document.readyState to determine whether or not you need to listen for that event at all.

    if( document.readyState !== 'loading' ) {
        console.log( 'document is already ready, just execute code here' );
        myInitCode();
    } else {
        document.addEventListener('DOMContentLoaded', function () {
            console.log( 'document was not ready, place code here' );
            myInitCode();
        });
    }
    
    function myInitCode() {}
    

提交回复
热议问题