When does document.ready actually fire?

后端 未结 4 752
野性不改
野性不改 2020-12-11 02:38

Let\'s consider the following case:

There is a 2.5MB image in an tag and I\'m on a slow connection which takes considerable time to download

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 02:59

    As in the Documentation:

    While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed.

    So it's when the tags are loaded, but not the actual data of the images.

    An example of loading the images and triggering an event when they are loaded:

    
    
    
    $(document).ready(function() {
      $("img").load(function() {
        alert('image loaded');
      }).each(function() {
        $(this).attr("src", $(this).attr("data-src"));
      });
    });
    

提交回复
热议问题