Official way to ask jQuery wait for all images to load before executing something

前端 未结 10 2342
攒了一身酷
攒了一身酷 2020-11-22 00:04

In jQuery when you do this:

$(function() {
   alert(\"DOM is loaded, but images not necessarily all loaded\");
});

It waits for the DOM to

10条回答
  •  鱼传尺愫
    2020-11-22 00:13

    With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).on("load", handler) to execute something when all other things are loaded as well, such as the images.

    The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN JPEG files (or other suitable ones):

    
        
            
            
        
            Hello
            
            
            // : 100 copies of this in total
            
        
    
    

    With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:

    $(document).ready(function() {
    

    into:

    $(window).on("load", function() {
    

    then the alert box doesn't appear until after the images are loaded.

    Hence, to wait until the entire page is ready, you could use something like:

    $(window).on("load", function() {
        // weave your magic here.
    });
    

提交回复
热议问题