Javascript load vs ready vs domready vs DOMContentLoaded events

前端 未结 4 1377
余生分开走
余生分开走 2021-02-01 19:01

I am a bit lost in the \"start up\" events - there are so many different events and are named differently in the DOM and in various frameworks like jQuery. What are all

4条回答
  •  花落未央
    2021-02-01 19:59

    In general, previosus answers are very good and full. But one important difference between .ready() and DOMContentLoaded event exists.

    Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.

    Ref. https://api.jquery.com/ready/

    As we see from this, .ready() is executed at least once in all cases.

    For example, in browser console we may define

    >> function sample()
    {
      console.log('This is sample.');
    
      $( document ).ready(function ()
      {
        console.log("Ready is working in all cases.")
      });  
    }
    undefined
    

    and in result we have

    >> sample();
    undefined
    This is sample. debugger eval code:3:11
    Ready is working in all cases. debugger eval code:7:13
    >> sample();
    undefined
    This is sample. debugger eval code:3:11
    Ready is working in all cases. debugger eval code:7:13
    

提交回复
热议问题