Skip to content

Instantly share code, notes, and snippets.

@cybear
Created July 7, 2012 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybear/3065786 to your computer and use it in GitHub Desktop.
Save cybear/3065786 to your computer and use it in GitHub Desktop.
image loader
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);
}
});
@mroderick
Copy link

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

@mroderick
Copy link

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?

@cybear
Copy link
Author

cybear commented Jul 8, 2012

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.

@cybear
Copy link
Author

cybear commented Jul 8, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment