0

I want to show the content after image_1 and image_2 are completely loaded. But, it is not working as expected

var loading = 0;

(function() {
  $(".image_1").on('load', function() {
    console.log('loading image_1');
    loading++;
    checkLoading();
  });

  $(".image_2").on('load', function() {
    console.log('loading image_2');
    loading++;
    checkLoading();
  });
})();

function checkLoading() {
  console.log('inside Loading check');
  if (loading == 2) {
    console.log('loading done' + loading);
    $('#loader-wrapper').fadeOut('fast').remove();
  }
}

This function is not working all the time. It is added in the footer of php file.

Sometimes, it removes the #loader-wrapper successfully. But few other times, #loader-wrapper is not removed from DOM and I don't see any console.log info on that time.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Mahesh
  • 1,503
  • 3
  • 22
  • 33
  • 2
    Maybe your self executing functions gets called before the images are on the page or the reverse, the images are already loaded, so the onload won't fire. – Mouser Oct 22 '17 at 09:50
  • How is the image getting loaded ...is it making an HTTP request ...?? If yes then use promise – Rohit Kumar Oct 22 '17 at 09:52
  • Images are just loaded in the img tag – Mahesh Oct 22 '17 at 09:58
  • 1
    @Mouser you are right. They must be loaded before the script starts to check. If found this. https://stackoverflow.com/questions/26980962/jquery-check-if-image-already-loaded-before-binding-a-load-event – Mahesh Oct 22 '17 at 10:02
  • You can check if the image is already loaded using e.g. `naturalWidth` as described here [Check if an image is loaded (no errors) in JavaScript](https://stackoverflow.com/questions/1977871), and if it is not loaded listen for the load event. – t.niese Oct 22 '17 at 10:04
  • how about the complete property? – Mahesh Oct 22 '17 at 10:05

1 Answers1

0

Since you've placed the script at the footer (end of document), my best guess is that the images are already loaded before the script is initiated. Hence, I dont think the .on("load", function(){ will ever be fired, as the load event simply doesn't happen after the script is initiated (it already has).

I've made a little demo fiddle here, as they (jsfiddle) also load the script after the images: this is the fiddle

Try calling your function earlier (before) the images and see if this doesn't fix your issue.

Chri.s
  • 1,386
  • 1
  • 12
  • 23