Ted M Ted M - 1 year ago 39
Javascript Question

Javascript pre-loader not waiting for images

I found this Javascript to activate my website's pre-loader. However, it seems to disappears once the page has loaded and not when images have finished loading.

After searching I found someone suggesting window.onload which waits until images have loaded, but I can't seem to figure out how to implement it into my existing Javascript.


Answer Source

If you would like to use the window.onload function to hide your preloader, you can attach to the event in jQuery using the following snippet:

$(window).on('load', function () {

Make sure to use the .on() method signature and not the event signature .load(), which was deprecated in jQuery 1.8 and removed in jQuery 3.0.

You should note the following from the .load() docs:

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