Created
August 1, 2013 13:29
-
-
Save motionharvest/6131326 to your computer and use it in GitHub Desktop.
Here is a pure javascript asset loader as a Curl.js module. You create a new instance of it each time you want to load assets. Pass it an object with an "assets", "onComplete", and optionally "onProgress" properties. It does the hard work for you.
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
define(function() { | |
function BulkLoader(options) { | |
new LoadingGroup(options.assets); | |
//Wrap the image loading so we can identify the asset | |
function ImageLoader(url, id, callback){ | |
var _id = id; | |
var _url = url; | |
var _img = new Image(); | |
_img.onload = function(){ | |
callback(_img, _id) | |
} | |
_img.src = url; | |
} | |
function LoadingGroup(images_array){ | |
var output_images = [], | |
i; | |
//store array of statuses | |
var loaded_status = []; | |
for(i = 0; i < images_array.length; i++){ | |
loaded_status[i] = false; | |
} | |
//generate new loaders. Have them check the status when they're done | |
for(i = 0; i < images_array.length; i++){ | |
new ImageLoader(images_array[i], i, checkStatus); | |
} | |
var filesLoaded = 0; | |
function checkStatus(imageData, id){ | |
//update its status | |
loaded_status[id] = true; | |
output_images[id] = imageData; | |
filesLoaded++; | |
if(options.hasOwnProperty("onProgress")){ | |
options.onProgress({ | |
loaded: filesLoaded, | |
total: images_array.length, | |
percentage: (filesLoaded / images_array.length) * 100, | |
id: id, | |
data: imageData | |
}); | |
} | |
//check if any status is still false | |
for(i = 0; i < loaded_status.length; i++){ | |
if(loaded_status[i] == false){ | |
return; | |
} | |
} | |
//if it makes it here, all images are loaded | |
options.onComplete(output_images); | |
} | |
} | |
} | |
//that's all. | |
return BulkLoader; | |
}) | |
/* | |
Implementation | |
*/ | |
//bulkloader example | |
var loadGroup = new BulkLoader({ | |
assets: ["../images/title_magic.png","../images/asfalt.png","../images/logo2.png","../images/logo.png"], | |
onComplete: function(images){ | |
console.log("images done"); | |
}, | |
onProgress: function(options){ | |
//an image is finished | |
console.log(options.percentage + '%'); | |
console.log(options.loaded + " of " + options.total + " images were loaded."); | |
console.log("#" + options.id + ":"); | |
console.log("data:", options.data); | |
switch(options.id){ | |
case 2: | |
console.log("The third image was finished loading") | |
break; | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment