I am trying to find an image preloader script.
While i found a few, none of them supports an event that is triggered when preloading is finished.
Does anyone know of any script or jQuery plugin that will do this?
Hope this question is appropriate for stackoverflow - if not, feel free to remove it in an instant.
Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM
<img>
elements indefinitely many times without replacing them.We may use the Fetch API to access the images, wait until they are all downloaded within a
promise.all()
and then in one go just replace thesrc
attributes of theimg
elements at the most suitable time by usingwindow.requestAnimationFrame()
.In the following example I refresh the
src
attributes of theimg
elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the samerefreshImagesNTimes
function recursively.You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple
setTimeout
mechanism.Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using
$("element").hide()
or something similar. Before you do this, attach a load event handler like so:Here's a function that will preload images from an array and call your callback when the last one has finished:
And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:
And, here's a version using 2015 jQuery promises:
For a more robust solution, consider this
PRELOADER
function with a couple of callbacks (jsFiddle).Keeping it simple:
In this example, I'm passing callbacks and an image hash inside an
Object
literalPRELOADER_OBJECT
, then overriding the callbacks insidePRELOADER
:};
With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.