Skip to content

Instantly share code, notes, and snippets.

@snorpey
Last active August 29, 2015 14:00
Show Gist options
  • Save snorpey/11205741 to your computer and use it in GitHub Desktop.
Save snorpey/11205741 to your computer and use it in GitHub Desktop.
AMD module for loading a file asynchronously. It also stores the file in the browsers local storage for quicker access. I mostly use it for loading GLSL shader files
/*global define*/
/*
AMD module for loading files asynchronously. It also stores the contents of the files
in the browsers local storage for quicker access. I mostly use it for loading GLSL
shader files. Note: This has not been tested extensively, so use with caution.
MIT License
*/
define(
function()
{
function FileLoader ()
{
var self = this;
var files = { };
var path_prefix = '';
var path_suffix = '';
var use_localstorage = ( window && localStorage && JSON );
if ( use_localstorage )
{
files = JSON.parse( localStorage.getItem( 'file-loader' ) ) || { };
}
function load ( requested_files, loaded, complete )
{
var files_to_load = [ ];
var files_arr = [ ];
var files_obj = [ ];
var files_loaded_count = 0;
var i = 0;
var len = 0;
if ( typeof requested_files === 'string' )
{
requested_files = [ requested_files ];
}
for ( i = 0, len = requested_files.length; i < len; i++ )
{
var file_name = requested_files[i];
if ( files_to_load.indexOf( file_name ) === -1 )
{
files_to_load.push( file_name );
}
}
for ( i = 0, len = files_to_load.length; i < len; i++ )
{
loadFile( files_to_load[i] );
}
function loadFile ( file_name )
{
if ( typeof files[file_name] !== 'undefined' )
{
fileLoaded( file_name, files[file_name] );
}
else
{
var request = new XMLHttpRequest();
request.onreadystatechange = function ()
{
if ( request.readyState === 4 )
{
fileLoaded( file_name, request.responseText );
}
};
request.open( 'GET', path_prefix + file_name + path_suffix );
request.send();
}
}
function fileLoaded ( file_name, file_content )
{
// account for multiple occurencies in files_requested
// but load them only once
var indexes = getIndexes( file_name, requested_files );
for ( var i = 0, len = indexes.length; i < len; i++ )
{
files_arr[indexes[i]] = file_content;
}
if ( typeof files[file_name] === 'undefined' )
{
files[file_name] = file_content;
files_obj[file_name] = files[file_name];
if ( use_localstorage )
{
localStorage.setItem( 'loader', JSON.stringify( files ) );
}
}
files_loaded_count++;
if ( typeof loaded === 'function' )
{
loaded( file_content );
}
if ( files_loaded_count === files_to_load.length )
{
if ( typeof callback === 'function' )
{
complete( files_obj, files_arr, requested_files );
}
}
}
}
function getIndexes ( val, arr )
{
var result = [ ];
for ( var i = 0, len = arr.length; i < len; i++ )
{
if ( arr[i] === val )
{
result.push( i );
}
}
return result;
}
self.load = load;
}
return new FileLoader().load;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment