Skip to content

Instantly share code, notes, and snippets.

@franklinjavier
Last active December 25, 2015 19:59
Show Gist options
  • Save franklinjavier/7032099 to your computer and use it in GitHub Desktop.
Save franklinjavier/7032099 to your computer and use it in GitHub Desktop.
Minimal image preload
/*
* Preload de imagens
*
* @param {array} imgs - Array com o path das imagens
* @example preload(['img/foto1.jpg', 'img/foto2.jpg']);
*/
function preload( imgs, fn ) {
var len = imgs.length,
totalLoaded = 0;
function loadImage() {
var img = new Image();
function noop() {}
img.error = function() {
preload();
};
img.onload = function() {
totalLoaded++;
try {
delete img.onload; // liberando memoria
} catch( err ) {
img.onload = noop; // IE7
}
if ( totalLoaded === len ) {
fn();
}
};
img.src = imgs[ i ];
}
for ( var i in imgs ) {
loadImage( i );
}
}
preload(['http://www.site.com/img1.jpg', 'http://www.site.com/img1.jpg'], function() {
console.log('carregou');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment