-
-
Save cybear/3065786 to your computer and use it in GitHub Desktop.
define( | |
function(){ | |
"use strict"; | |
return function(urls, success){ | |
var imgs, counter=0; | |
function isEverythingDone(){ | |
counter++; | |
console.log('Loaded '+counter+' of '+urls.length+': '+this.src+' '+this.width+'*'+this.height); | |
if(counter == urls.length) { | |
success(imgs); | |
} | |
} | |
function urlToImgElement(url){ | |
var el=new Image(); | |
el.src=url; | |
el.onload=isEverythingDone; | |
return el; | |
} | |
console.log('Attempting to load '+urls.length+' images...'); | |
imgs = urls.map(urlToImgElement); | |
} | |
}); |
Also, you could name the function that is returned, to make it easier to debug code in the future?
Since you're not actually doing anything with the imgs
variable, perhaps it would be better to use forEach
... or even use a for loop, and be ES3 (and IE) compatible?
Yeah, I was considering adding some error handling - the onerror was actually used but never made it into this example. Your Preloadr library looks interesting :)
Naming a function, yes. How I reasoned was that you already have the filenames in require.js as sort of the official module names, so I figured the function name would be redundant. But then again, as a developer, you would have to always look up at the filename to know which file you are working on. Maybe not optimal.
With regards to your last comment; I am actually passing on the imgs variable to the success callback.
With regards to ES3, I prefer to code for newer and use polyfills for older browsers. I am aware that polyfills are not always 100% identical to the real thing, however for my coding style it usually seems to work.
If any of the urls fail to load, your callback will never be called.
There is an onerror callback on Image, perhaps you can use that?
See https://github.com/mroderick/Preloadr/blob/master/src/preloadr.js