How to preload images in html with javascript and storage (asynchronously).
const preloadImage = src => new Promise((resolve, reject) => {
const image = new Image()
image.onload = resolve
image.onerror = reject
image.src = src
})// Image from Storage
let arr = [
{name: 'Gif 1', image: '/media/gifs/1.gif'},
{name: 'Gif 2', image: '/media/gifs/2.gif'},
]
// Preload with url
arr.forEach(g => {
let path = '/img/gif?path=' + g.image;
preloadImage(path).then(p => console.log("Preloading" , path))
});// Get json
async function gifs() {
const r = await fetch('/all/gifs');
return await r.json()
}
// Promise
let list = gifs();
list.then(arr => {
arr.forEach(g => {
let path = '/img/gif?path=' + g.image;
preloadImage(path).then(p => console.log("Preloading" , path))
});
});function displayGif(Request $request)
{
try {
$path = $request->input('path');
if (Storage::exists($path)) {
return Storage::response($path);
}
return response()->file(public_path('/default/default.gif'));
} catch (Throwable $e) {
return response()->file(public_path('/default/error.webp'));
}
}