jQuery .load() function after ajax completes. Don't show images until 100% loaded

StackOverflow https://stackoverflow.com/questions/8874263

  •  28-10-2019
  •  | 
  •  

Вопрос

I'm using the ajaxify-html5.js script found here: https://github.com/browserstate/ajaxify

The script is working great, except that when the content is loaded in (around line 145: $content.html(contentHtml).ajaxify(); ) you can still see the images loading. I would like to create a function which removes the "loading" class (which fades in and out the content with a CSS transition) but only once the ajax content is not just fetched, but completely loaded, to avoid showing partially loaded images.

I've tried inserting the following on line 146 but it doesn't get executed.

$content.load(function(){
    alert('asds');
    $body.removeClass('loading');
});

Any ideas?

Thanks!


UPDATE: Final working code based on Karim's answer:

$content.html(contentHtml).ajaxify(); /* you could fade in here if you'd like */

var $imgs = $content.find("img");
var loadCounter = 0;
var nImages = $imgs.length;
$imgs.load(function () {
    loadCounter++;
    if(nImages === loadCounter) {
        $body.removeClass("loading");
    }

// trigger load event if images have
// been cached by the browser
}).each(function () {
    if(this.complete) {
        $(this).trigger("load");   
    }
});
Это было полезно?

Решение

I am not certain how this would fit in to that plugin, but a general solution which I use in such situations (I have adapted it to fit your situation to the best of my ability) is as follows:

$content.one("load", function() {
    var $imgs = $(this).find("img");
    $imgs.hide();
    var loadCounter = 0;
    var nImages = $imgs.length;
    $imgs.load(function () {
        loadCounter++;
        if(nImages === loadCounter) {

            // all the images have loaded
            // reveal them, remove the loading indicator
            $body.removeClass("loading");
            $imgs.show(); 
        }

    // trigger load event if images have
    // been cached by the browser
    }).each(function () {
        if(this.complete) {
            $(this).trigger("load");   
        }
    });
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top