Skip to content

Instantly share code, notes, and snippets.

@tobalsan
Last active August 29, 2015 14:04
Show Gist options
  • Save tobalsan/10026ea7db2d68e4ceec to your computer and use it in GitHub Desktop.
Save tobalsan/10026ea7db2d68e4ceec to your computer and use it in GitHub Desktop.
JavaScript: Preload images at loading
// Prelod a single image
var image = $('<img />').attr('src', '/path/to/image.png');
// Multiple images
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
/* OR TURN IT INTO A PLUGIN */
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment