It's a small library for preload images in browser.
Large or a lot of image files may take a second or two to load on the page. Preloading those images early rather than later helps ensure that visitors have a great experience viewing your content.
JavaScript includes the Image among its native object types. The Image object represents an HTML image tag on the page and exposes the same properties and events. Perhaps oddly, the Image has no constructor that accepts an image source, so an image must be loaded into the object by setting its src attribute. Doing so causes the image to be downloaded from the server at that point.
First image receive src after loading and second was added dynamically:
import preload from '@bautrukevich/preload';
const IMAGE_URL = 'https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
preload(IMAGE_URL).then(loaded => {
console.log(loaded); // [[HTMLImageElement, 'loaded']]
let loadedImageElement = loaded[0][0];
let image = document.getElementById('image');
// Firs image
let inserted = image.parentNode.insertBefore(loadedImageElement, image.nextSibling);
inserted.height = 44;
// Second image
image.src = loadedImageElement.src;
}, failed => {
console.log(failed);
});
import preload from '@bautrukevich/preload';
const IMAGE_URL = 'https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
const FAILED_IMAGE_URL = 'https://www.google.ru/images/branding/googlelogo/2x.jpg';
let orImageWithSrc = new Image();
let orImageWithoutSrc = new Image(); // it's valid and you can set src later
orImageWithSrc.src = IMAGE_URL;
// It would be resolved
preload(IMAGE_URL, orImageWithSrc).then(resolved => {
console.log(resolved); // [[HTMLImageElement, 'loaded'], [HTMLImageElement, 'loaded']]
}, rejected => {
console.log(rejected);
});
// It would be rejected
preload(orImageWithoutSrc).then(resolved => {
console.log(resolved);
}, rejected => {
console.log(rejected); // [[HTMLImageElement, 'new']]
});
// It would be rejected — if at least one image was not loaded
preload(IMAGE_URL, orImageWithoutSrc).then(resolved => {
console.log(resolved);
}, rejected => {
console.log(rejected); // [[HTMLImageElement, 'loaded'], [HTMLImageElement, 'new']]
});
// It would be rejected — if at least one image was not loaded
preload(FAILED_IMAGE_URL, orImageWithSrc).then(resolved => {
console.log(resolved);
}, rejected => {
console.log(rejected); // [[HTMLImageElement, 'failed'], [HTMLImageElement, 'loaded']]
});