Preloading images with JavaScript

Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
    var img=new Image();

I have an array of image URLs that I loop over and call the preloadImage function for each URL.

Yes. This should work on all major browsers.

Try this I think this is better.

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];

//-- usage --//


In my case it was useful to add a callback to your function for onload event:

function preloadImage(url, callback)
    var img=new Image();
    img.onload = callback;

And then wrap it for case of an array of URLs to images to be preloaded with callback on all is done:

function preloadImages(urls, allImagesLoadedCallback){
    var loadedCounter = 0;
  var toBeLoadedNumber = urls.length;
    preloadImage(url, function(){
            console.log('Number of loaded images: ' + loadedCounter);
      if(loadedCounter == toBeLoadedNumber){
  function preloadImage(url, anImageLoadedCallback){
      var img = new Image();
      img.onload = anImageLoadedCallback;
      img.src = url;

// Let's call it:
], function(){
    console.log('All images were loaded');

CSS2 Alternative:

body:after {
  content: url(img01.jpg) url(img02.jpg) url(img03.jpg);
  display: none; 

CSS3 Alternative: (H/T Linh Dam)

.preload-images {
  display: none; 
  width: 0;
  height: 0;
  background: url(img01.jpg),

NOTE: Images in a container with display:none might not preload. Perhaps visibility:hidden will work better but I have not tested this. Thanks Marco Del Valle for pointing this out

I recommend you use a try/catch to prevent some possible issues:


    var preloadImage = function (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }


    function preloadImage (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }

Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.

This approach is a little more elaborate. Here you store all preloaded images in a container, may be a div. And after you could show the images or move it within the DOM to the correct position.

function preloadImg(containerId, imgUrl, imageId) {
    var i = document.createElement('img'); // or new Image() = imageId;
    i.onload = function() {
         var container = document.getElementById(containerId);
    i.src = imgUrl;

Try it here, I have also added few comments

Yes this will work, however browsers will limit(between 4-8) the actual calls and thus not cache/preload all desired images.

A better way to do this is to call onload before using the image like so:

function (imageUrls, index) {  
    var img = new Image();

    img.onload = function () {
        console.log('isCached: ' + isCached(imageUrls[index]));

    img.src = imageUrls[index]

function isCached(imgUrl) {
    var img = new Image();
    img.src = imgUrl;
    return img.complete || (img .width + img .height) > 0;

Here is my approach:

var preloadImages = function (srcs, imgs, callback) {
    var img;
    var remaining = srcs.length;
    for (var i = 0; i < srcs.length; i++) {
        img = new Image;
        img.onload = function () {
            if (remaining <= 0) {
        img.src = srcs[i];

Solution for ECMAScript 2017 compliant browsers

Note: this will also work if you are using a transpiler like Babel.

'use strict';

function imageLoaded(src, alt = '') {
    return new Promise(function(resolve) {
        const image = document.createElement('img');

        image.setAttribute('alt', alt);
        image.setAttribute('src', src);

        image.addEventListener('load', function() {

async function runExample() {
    console.log("Fetching my cat's image...");

    const myCat = await imageLoaded('');

    console.log("My cat's image is ready! Now is the time to load my dog's image...");

    const myDog = await imageLoaded('');

    console.log('Whoa! This is now the time to enable my galery.');



You could also have waited for all images to load.

async function runExample() {
    const [myCat, myDog] = [
        await imageLoaded(''),
        await imageLoaded('')


Or use Promise.all to load them in parallel.

async function runExample() {
    const [myCat, myDog] = await Promise.all([


More about Promises.

More about "Async" functions.

More about the destructuring assignment.

More about ECMAScript 2015.

More about ECMAScript 2017.

const preloadImage = src => 
  new Promise(r => {
    const image = new Image()
    image.onload = r
    image.onerror = r
    image.src = src

// Preload an image
await preloadImage('')

// Preload a bunch of images in parallel 
await Promise.all( => preloadImage(x.src)))

I can confirm that the approach in the question is sufficient to trigger the images to be downloaded and cached (unless you have forbidden the browser from doing so via your response headers) in, at least:

  • Chrome 74
  • Safari 12
  • Firefox 66
  • Edge 17

To test this, I made a small webapp with several endpoints that each sleep for 10 seconds before serving a picture of a kitten. Then I added two webpages, one of which contained a <script> tag in which each of the kittens is preloaded using the preloadImage function from the question, and the other of which includes all the kittens on the page using <img> tags.

In all the browsers above, I found that if I visited the preloader page first, waited a while, and then went to the page with the <img> tags, my kittens rendered instantly. This demonstrates that the preloader successfully loaded the kittens into the cache in all browsers tested.

You can see or try out the application I used to test this at

Note in particular that this technique works in the browsers above even if the number of images being looped over exceeds the number of parallel requests that the browser is willing to make at a time, contrary to what Robin's answer suggests. The rate at which your images preload will of course be limited by how many parallel requests the browser is willing to send, but it will eventually request each image URL you call preloadImage() on.

You can move this code to index.html for preload images from any url

<link rel="preload" href="" as="image">

The browser will work best using the link tag in the head.

export function preloadImages (imageSources: string[]): void {
    .forEach(i => {
      const linkEl = document.createElement('link');
      linkEl.setAttribute('rel', 'preload');
      linkEl.setAttribute('href', i);
      linkEl.setAttribute('as', 'image');

Working solution as of 2020

Most answers on this post no longer work - (atleast on Firefox)

Here's my solution:

var cache = document.createElement("CACHE"); = "position:absolute;z-index:-1000;opacity:0;";
function preloadImage(url) {
    var img = new Image();
    img.src = url; = "position:absolute";



Obviously <cache> is not a "defined" element, so you could use a <div> if you wanted to.

Use this in your CSS, instead of applying the style attribute:

cache {
    position: absolute;
    z-index: -1000;
    opacity: 0;

cache image {
    position: absolute;

If you have tested this, please leave a comment.


  • Do NOT apply display: none; to cache - this will not load the image.
  • Don't resize the image element, as this will also affect the quality of the loaded image when you come to use it.
  • Setting position: absolute to the image is necessary, as the image elements will eventually make it's way outside of the viewport - causing them to not load, and affect performance.


While above solution works, here's a small update I made to structure it nicely:

(This also now accepts multiple images in one function)

var cache = document.createElement("CACHE");
function preloadImage() {
    for (var i=0; i<arguments.length; i++) {
        var img = new Image();
        img.src = arguments[i];
        var parent = arguments[i].split("/")[1]; // Set to index of folder name
        if ($(`cache #${parent}`).length == 0) {
            var ele = document.createElement("DIV");
   = parent;
        $(`cache #${parent}`)[0].appendChild(img);



enter image description here