Shortcuts for jQuery's ready() method

后端 未结 3 1676
春和景丽
春和景丽 2020-12-12 20:45

I have seen some shortcuts for the ready() method and would like to know which actually happens first, because my test results confuse me..

$(document).ready         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-12 21:15

    This article has a good explanation on how the first two are different:

    $(document).ready vs. $(window).load

    jQuery offers two powerful methods to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven't loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

    $(document).ready(function() {
      // executes when HTML-Document is loaded and DOM is ready
      alert("document is ready");
    });
    

    The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.

    $(window).load(function() {
      // executes when complete page is fully loaded, 
      // including all frames, objects and images
      alert("window is loaded");
    });
    

提交回复
热议问题