Skip to content

Instantly share code, notes, and snippets.

@caubry
Last active January 3, 2016 22:39
Show Gist options
  • Save caubry/8529666 to your computer and use it in GitHub Desktop.
Save caubry/8529666 to your computer and use it in GitHub Desktop.
var gCachedAssets = {};
function loadAssets(assetList, callbackFcn) {
var loadBatch = {
count: 0,
total: assetList.length,
cb: callbackFcn
};
for(var i = 0; i < assetList.length; i++) {
if(gCachedAssets[assetList[i]] == null) {
var assetType = getAssetTypeFromExtension(assetList[i]);
if(assetType === 0) { // Asset is an image
var img = new Image();
img.onload = function () {
onLoadedCallback(img, loadBatch);
};
img.src = assetList[i];
gCachedAssets[assetList[i]] = img;
} else if(assetType === 1) { // Asset is Javascript
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.onload = function (e){
onLoadedCallback(fileref,loadBatch);
};
fileref.setAttribute("src", assetList[i]);
document.getElementsByTagName("head")[0].appendChild(fileref);
gCachedAssets[assetList[i]] = fileref;
}
} else { // Asset is already loaded
onLoadedCallback(gCachedAssets[assetList[i]], loadBatch);
}
}
}
function onLoadedCallback(asset, batch) {
batch.count++;
if(batch.count == batch.total) {
batch.cb(asset);
}
}
function getAssetTypeFromExtension(fname) {
if(fname.indexOf('.jpg') != -1 || fname.indexOf('.jpeg') != -1 || fname.indexOf('.png') != -1 || fname.indexOf('.gif') != -1 || fname.indexOf('.wp') != -1) {
// It's an image!
return 0;
}
if(fname.indexOf('.js') != -1 || fname.indexOf('.json') != -1) {
// It's javascript!
return 1;
}
// Uh Oh
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment