Search code examples
javascriptimagepreloader

Function firing before images has finished loading


I'm trying to get a pre loader screen to work but am hitting a roadblock.

My goal: To have the loading animation/divs dissapear when the image has finished loading.

I've tried to accomplish this with a simple .ready function and still the function that removes the loading animation fires white the image is still loading and the viewer will see the image load in real time.

$("#defaultImage").ready(function(){
  TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
  console.log('Page has loaded'); 
});

Is this incorrect? I thought that this will wait for the entire page(images included) to load and then fire the function inside it.

I've tried the below too and it doesn't seem to fire the console.log at all

document.getElementById("defaultImage").onload = function (){
  console.log('Page has loaded'); 
};

Pen in question below. You can see the issue if you view it in debug view and do a hard refresh. http://codepen.io/mhcreative/pen/GoxLPo?editors=0011

Any help would be much appreciated.

Thanks, All.


Solution

  • Here try this if you still want it natively.

    $(document).ready(function(){
        var img = new Image();   // Create new img element
        img.addEventListener("load", function() {
         TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
        }, false);
        img.src = 'src/to/img'; // Set source path
        $("#defaultImage").append(img); //append loaded image inside div
    });