Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active December 13, 2016 22:37
Show Gist options
  • Save Anthodpnt/d3db0f417bf9481e9a2093fe3a6f7eb7 to your computer and use it in GitHub Desktop.
Save Anthodpnt/d3db0f417bf9481e9a2093fe3a6f7eb7 to your computer and use it in GitHub Desktop.
Misc - Image Loader
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <[email protected]>
* @site: https://www.twitter.com/JsGists
*
* We you build your project you sometimes need to load (you should load) your assets.
* One of the main type of asset you're using is `images` and if you don't load them
* it could easily destroy your user experience.
* I will not show you how to create a complete loader, I'll only show you how to code
* a simple loader to load your images.
*
* Example:
* I have a single-page website with 4 images and I want to load them before showing
* the page.
**/
// We define the relative path to images we want to load.
const images = ['path/to/image-1.jpg', 'path/to/image-2.png', 'path/to/image-3.gif', 'path/to/image-4.jpg'];
// We also define a counter to know how many images are loaded and
// a progress variable to store the progress in %;
let loaded = 0;
let progress = 0;
const length = images.length;
for (let i = 0; i < length; i++) {
// The trick is to create an image element for each entry of our array
// in JS with `new Image()`.
// This create a `<img>` element which won't be added to our DOM but
// we will use to know when the image is loaded.
const image = new Image();
// The `onload` method is then bound to our image element and will fire
// when the image is loaded.
image.onload = () => {
loaded += 1; // We update our counter;
progress = Math.floor((loaded / length) * 100); // We update the progress to x%
if (loaded === length) {
console.log('Loading completed, show the page!');
}
};
// Finally we need to set the `src` attribute of our image element to
// load something. For each entry of our array the `src` attribute
// will be `path/to/image-1.jpg` then `path/to/image-2.png`...
image.src = images[i];
// Notice that you have to define the `src` attribute after the `onload`
// method because you image will start loading as soon as the `src` attribute
// will be set and when it will be loaded the `onload` method has to be defined.
// If the onload function is defined after the `src` attribute, nothing will
// happen when the image will be loaded. Please contact me if you need more
// informations about that. <[email protected]>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment