ajaxjqueryblockuijquery-blockui

Jquery BlockUI - Wait for images before unblocking on ajax load


I'm using the BlockUI jquery plugin to show a loading message in a div until the content is loaded using JQuery's load method.

The problem is, the content I'm pulling in contains images. The load callback fires before the images are fully loaded and the div is unblocked too early.

Is there a way I can wait for all the images to load before BlockUI unblocks the div?

Alternatively, if I can override the unblocking I can do the following, using the waitForImages plugin

$('#mydiv').block({ message: 'Loading' }); 

$('#mydiv').load('ajax.php', function() {
   $('#mydiv').waitForImages(function() {
      $('#mydiv').unblock();
   });
});

Solution

  • I reckon you should wrap your DIV #mydiv inside another DIV.

    $.getJSON("http://api.flickr.com/services/feeds/photoset.gne?set=72157623591220769&nsid=21696934@N05&format=json&jsoncallback=?", function(data) {
        $.each(data.items, function(i, item) {
            $("<option>").attr("value", item.media.m).html('image ' + i).appendTo("#imagesLink");
        });
    
    });
    
    $("#imagesLink").on('change', function() {
    
        $('#mydivContainer').block({
            message: 'Loading'
        });
    
        setTimeout(LoadImage, 10, this.value);
    
    });
    
    function LoadImage(imagePath)
    {
        $('#mydiv').html($('<img>').attr('src', imagePath));
        
        $('#mydiv img').waitForImages(function() {
            $('#mydivContainer').unblock();
            // alert("Finished!");
        });
        
    }
    #mydivContainer
    {
        width: 400px;
        height: 400px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://malsup.github.io/jquery.blockUI.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/2.4.0/jquery.waitforimages.js"></script>
    
    choose an image <select id="imagesLink"></select>
    <div id="mydivContainer">
        <div id="mydiv"></div>
    </div>

    Or a fiddle jsFiddle where you can test it.