Wait for images to load and then execute all other code

后端 未结 6 1649
广开言路
广开言路 2021-02-14 14:24

OK, I\'m losing my mind over this. I did read here at SO and google about it, I even have the preloader set (found here on SO), but none of the plugins/code I found helped me. <

相关标签:
6条回答
  • 2021-02-14 14:54

    You could display the image only once it is loaded like so :

    <img src="hdimg.jpg" width="1920" height="1080" style="display:none;" id="img1">
    
    <script type="text/javascript">
    $('#img1').load(function(){
        $(this).css({'display':'block'})
    });
    </script>
    
    0 讨论(0)
  • 2021-02-14 14:55

    I think what you're looking for is javascript:onLoad(), which gets called as soon as the browser finishes loading.

    0 讨论(0)
  • 2021-02-14 14:57

    The waitForImages pluggin is an interesting one, but the solution can be achieved just with:

        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');
        }).each(function() {
          this.complete && $(this).load();        
        });
    
    0 讨论(0)
  • 2021-02-14 14:58

    I have a plugin named waitForImages that lets you attach a callback when descendent images have loaded.

    In your case, if you wanted to wait for all assets to download, $(window).load() may be fine. But you could do it a bit cooler with my plugin :)

    var loading = $('#loading');
    
    $('body').waitForImages(function()
    {    
        loading.addClass('hidden');  
    }, function(loaded, total)
    {
        loading.html(loaded + ' of ' + total);
    
    });
    
    0 讨论(0)
  • 2021-02-14 15:01

    I believe the best jQuery option is to use the ajax get call:

    $.get('image.png', {}, function(){
        // Do whatever you want here, this wont execute until image.png is preloaded
    });
    
    0 讨论(0)
  • 2021-02-14 15:14

    Instead of trying to preload, you could just execute your script on...

    window.onload = function(){..}
    

    That doesn't fire until all images have been loaded.

    0 讨论(0)
提交回复
热议问题