I have a hard time getting my head around how image preloaders work in java-script. So if someone could could explain how they work with an example that would help a lot. no jquery
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- void before promise syntax
Loading a single image
The browser will load images asynchronously...meaning when the browser is given the
.src
of an image, it will start loading that image in the background, but will also continue processing the javascript code directly after.src
The alert will display even before the image is fully loaded and ready to use.
So how do you know when the image is fully loaded and ready to use?
Answer: You can tell the browser to "call you back" when it finishes loading the image. You get "called back" by adding an "img.onload" function on the image object. Whenever the browser finishes loading the image, the browser will trigger the code in the "img.onload" function.
The complete image loading process will occur in this sequence:
Pre-loading multiple images
To preload multiple images:
Create an array to hold all your image URLs and add your image URLs to this array.
Create an array to hold all your image objects (==your actual images).
Add
new Image
elements to the image object array (add onenew Image
for each URL in the URL array).Set every image object's
.onload
callback to the same function.Use the image URL array to set the
.src
of each image to the individual url.In the
theImageHasFinishedLoading
callback, increment a counter every time a new image is successfully loaded.You will know that all images are fully loaded when the counter reaches the same length as your image URL array.
Here's a full example code and a Demo: