0

Hi I'm attempting to prevent an animation from occurring until after images that are being pulled from a separate html document are fully loaded.

As far as I can tell, right now, the code is saying: load div with id of "images" then run function. I guess what I want it to say is pull id of images, wait for images to load fully, then run function. Help is much appreciated.

$('#nav a, .section a').click(function(event) {
event.preventDefault();

$('.project-detail').load(this.href + " #images", function() {
    $('.project-detail').removeClass('no-transition');
    $('.project-detail').addClass('move-left');
    $('#close-tag').addClass('desktop-close-move');
    $('#doit').addClass('close-move');
});

});
Alaw16
  • 37
  • 5
  • The callback for `load` gets fired after the HTML source has been downloaded and applied; images, as you are experiencing, get loaded afterwards. – qxz Aug 05 '16 at 01:26
  • Also, that will load the entire page at, say, `http://www.example.com/ #images`, not select the `#images` div. You could try loading the page into a hidden element, then get the div with your selector, then add it into the real page – qxz Aug 05 '16 at 01:29
  • [JavaScript Preloading Images](http://stackoverflow.com/questions/3646036/javascript-preloading-images) – Ronnie Royston Aug 05 '16 at 03:04

2 Answers2

2

Bind a load event handler to your images which will be executed when images are loaded and thus run your animations.

$(your_images).load(function() {
  //run your animations here when images are loaded
});
kyw
  • 6,685
  • 8
  • 47
  • 59
0

Code that needs to be run only after everything else on the page has been fully loaded can be bound to the window like so...

$(window).on("load", function() {
    // after everything has fully loaded, do this
});

From the jQuery docs...

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object. https://api.jquery.com/load-event/

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

Image Caching Issues

imagesLoaded - jQuery Plugin

Community
  • 1
  • 1
Kenneth Stoddard
  • 1,409
  • 11
  • 13