Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Last active October 24, 2025 10:22
Show Gist options
  • Select an option

  • Save atomjoy/f5b50645b077bc47ed48d1abb25dd13d to your computer and use it in GitHub Desktop.

Select an option

Save atomjoy/f5b50645b077bc47ed48d1abb25dd13d to your computer and use it in GitHub Desktop.
Preload images in javascript.

Preload Images JS

How to preload images in html with javascript and storage (asynchronously).

Function

const preloadImage = src => new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = resolve
    image.onerror = reject
    image.src = src
})

From array

// 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))
});

From request

// 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))
    });
});

Route img/gif?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'));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment