Wait for images to load and then execute all other code

↘锁芯ラ 提交于 2019-12-03 12:34:38

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.

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);

});

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

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>

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();        
    });

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
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!