Skip to main content

jquery add image to browser cache

Sam Deering
Share

This is how you might preloading images using jQuery to add the images to browser cache (as part of a DOM div element which is hidden).

(function($,D,W) {

    var JQUERY4U = {};

    JQUERY4U.UTIL = {

        images:
        {
            loadingImage: '<img class="loading" src="images/loading.gif" alt="loading" />',
            ajaxImage: '<img class="msg-loading" src="images/ajax-loader.gif" alt="" />',
            savingImage: '<img class="loading" src="images/saving.gif" alt="saving" />'
        },

        preloadImages: function()
        {
            $('body').append('<div id="img-cache" style="display:none></div>');
            $.each(JQUERY4U.UTIL.images, function(i,v)
            {
                $('#img-cache').append(v);
            });
        }

    }

    $(D).ready(function($) {
        JQUERY4U.UTIL.preloadImages(); //preload images in browser cache
    });

})(jQuery,document,window);

Other techniques

// Array of images:
var imageArray = ['image1.jpeg', 'image2.png', 'image3.gif'];

// Loop through and declare an element that will not actually be used.
$.each(imageArray, function (i, val) {
  $('<img />').attr('src', val);
});