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

前端 未结 10 2340
攒了一身酷
攒了一身酷 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):

    <html>
        <head>
            <script src="jquery-1.7.1.js"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    alert ("done");
                });
            </script>
        </head><body>
            Hello
            <img src="jollyroger00.jpg">
            <img src="jollyroger01.jpg">
            // : 100 copies of this in total
            <img src="jollyroger99.jpg">
        </body>
    </html>
    

    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.
    });
    
    0 讨论(0)
  • 2020-11-22 00:13

    This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.

    var counter = 0;
    var size = $('img').length;
    
    $("img").load(function() { // many or just one image(w) inside body or any other container
        counter += 1;
        counter === size && $('body').css('background-color', '#fffaaa'); // any action
    }).each(function() {
      this.complete && $(this).load();        
    });
    
    0 讨论(0)
  • 2020-11-22 00:16

    Use imagesLoaded PACKAGED v3.1.8 (6.8 Kb when minimized). It is relatively old (since 2010) but still active project.

    You can find it on github: https://github.com/desandro/imagesloaded

    Their official site: http://imagesloaded.desandro.com/

    Why it is better than using:

    $(window).load() 
    

    Because you may want to load images dynamically, like this: jsfiddle

    $('#button').click(function(){
        $('#image').attr('src', '...');
    });
    
    0 讨论(0)
  • 2020-11-22 00:17

    I would recommend using imagesLoaded.js javascript library.

    Why not use jQuery's $(window).load()?

    As ansered on https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951

    It's a matter of scope. imagesLoaded allows you target a set of images, whereas $(window).load() targets all assets — including all images, objects, .js and .css files, and even iframes. Most likely, imagesLoaded will trigger sooner than $(window).load() because it is targeting a smaller set of assets.

    Other good reasons to use imagesloaded

    • officially supported by IE8+
    • license: MIT License
    • dependencies: none
    • weight (minified & gzipped) : 7kb minified (light!)
    • download builder (helps to cut weight) : no need, already tiny
    • on Github : YES
    • community & contributors : pretty big, 4000+ members, although only 13 contributors
    • history & contributions : stable as relatively old (since 2010) but still active project

    Resources

    • Project on github: https://github.com/desandro/imagesloaded
    • Official website: http://imagesloaded.desandro.com/
    • Check if an image is loaded (no errors) in JavaScript
    • https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
    • imagesloaded javascript library: what is the browser & device support?
    0 讨论(0)
  • 2020-11-22 00:20

    I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.

    It is similar to $(window).load(function() { .. }), except it lets you define any selector to check. If you only want to know when all images in #content (for example) have loaded, this is the plugin for you.

    It also supports loading of images referenced in the CSS, such as background-image, list-style-image, etc.

    waitForImages jQuery plugin

    • GitHub repository.
    • Readme.
    • Production source.
    • Development source.

    Example Usage

    $('selector').waitForImages(function() {
        alert('All images are loaded.');
    });
    

    Example on jsFiddle.

    More documentation is available on the GitHub page.

    0 讨论(0)
  • 2020-11-22 00:21

    My solution is similar to molokoloco. Written as jQuery function:

    $.fn.waitForImages = function (callback) {
        var $img = $('img', this),
            totalImg = $img.length;
    
        var waitImgLoad = function () {
            totalImg--;
            if (!totalImg) {
                callback();
            }
        };
    
        $img.each(function () {
            if (this.complete) { 
                waitImgLoad();
            }
        })
    
        $img.load(waitImgLoad)
            .error(waitImgLoad);
    };
    

    example:

    <div>
        <img src="img1.png"/>
        <img src="img2.png"/>
    </div>
    <script>
        $('div').waitForImages(function () {
            console.log('img loaded');
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题