Preloading images with jQuery ¶
Static preloading (in page HEAD)
<head> ... <link rel="subresource" href="{{ placeholder_url }}"> <link rel="subresource" href="{{ placeholder_empty_url }}">
Dynamic preloading
Strategy: append new hidden images to page body
// Support for image pre-fetching: // https://stackoverflow.com/questions/476679/preloading-images-with-jquery#comment16308902_476679#7311452 // // ... From my experience, preloading an image into the DOM makes the browser aware // of its existence and for it to be properly cached. // Otherwise, the image only exists in memory which only works for single page apps. // When appended to body it will work also on mobile. function check_preloaded(src) { // Check if specified image has already been preloaded var found = false; var array = $('img.preloaded_image'); var n = array.length; for (var i = 0; i < n && !found; ++i) { if ($(array[i]).attr('src') == src) { found = true; } } return found; } function preload(arrayOfImages) { // Preload the list of images $(arrayOfImages).each(function(index, item) { if (!check_preloaded(item)) { console.log('preload img: %o ...', item); $('<img class="preloaded_image" />').attr('src', item).appendTo('body').hide(); } else { console.log('preloaded : %o ...', item); } }); }
Credits: