Last active
December 25, 2015 19:59
-
-
Save franklinjavier/7032099 to your computer and use it in GitHub Desktop.
Minimal image preload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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