Code inside DOMContentLoaded event not working

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

I have used




  


  
相关标签:
7条回答
  • 2020-12-04 20:12

    Thanks to Ruslan & here is the full code snippet with the convenient detach of the DOMContentLoaded handler after it is used.

    'use strict';
    var dclhandler = false;
    if (document.readyState !== 'loading') {
        start();
    } else {
        dclhandler = true;
        document.addEventListener('DOMContentLoaded', start);
    }
    function start() {
        if (dclhandler) { document.removeEventListener('DOMContentLoaded', start); }
        console.log('Start the site`s JS activities');
    }
    
    0 讨论(0)
  • 2020-12-04 20:14

    The event has already fired by the time that code hooks it. The way Babel standalone works is by responding to DOMContentLoaded by finding and executing all of the type="text/babel" scripts on the page. You can see this in the index.js file:

    // Listen for load event if we're in a browser and then kick off finding and
    // running of scripts with "text/babel" type.
    const transformScriptTags = () => runScripts(transform);
    if (typeof window !== 'undefined' && window && window.addEventListener) {
      window.addEventListener('DOMContentLoaded', transformScriptTags, false);
    }
    

    Just run the code directly, without waiting for the event, since you know Babel standalone will wait for it for you.

    Also note that if you put you script at the end of the body, just before the closing </body> tag, there's no need to wait for DOMContentLoaded even if you don't use Babel. All of the elements defined above the script will exist and be available to your script.


    In a comment you've asked:

    But I am using Babel standalone in development, but I will pre-compile it when I go into production. Should I add it back on when I go into production?

    Just ensure that your script tag is at the end of body as described above, and there's no need to use the event.

    If it's important to you to use it anyway, you can check to see whether the event has already run by checking document.readyState (after following the link, scroll up a bit):

    function onReady() {
        // ...your code here...
    }
    if (document.readyState !== "loading") {
        onReady(); // Or setTimeout(onReady, 0); if you want it consistently async
    } else {
        document.addEventListener("DOMContentLoaded", onReady);
    }
    

    document.readyState goes through these stages (scroll up slightly from the link above):

    Returns "loading" while the Document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

    0 讨论(0)
  • 2020-12-04 20:22

    https://learnwithparam.com/blog/vanilla-js-equivalent-of-jquery-ready/

    function ready(callbackFunc) {
      if (document.readyState !== 'loading') {
        // Document is already ready, call the callback directly
        callbackFunc();
      } else if (document.addEventListener) {
        // All modern browsers to register DOMContentLoaded
        document.addEventListener('DOMContentLoaded', callbackFunc);
      } else {
        // Old IE browsers
        document.attachEvent('onreadystatechange', function() {
          if (document.readyState === 'complete') {
            callbackFunc();
          }
        });
      }
    }
    
    ready(function() {
      // your code here
    });

    0 讨论(0)
  • 2020-12-04 20:23

    My clean aproach...

    if (document.readyState !== 'loading') init()
    else document.addEventListener('DOMContentLoaded', init);
    
    function init() {
        console.log("Do it !");
        ...
    }
    
    0 讨论(0)
  • 2020-12-04 20:26

    I would use document.addEventListener("DOMContentLoaded", () => {/*yourcode*/});

    0 讨论(0)
  • 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() {}
    
    0 讨论(0)
提交回复
热议问题