LoaderJS
A customizable resource loader for web applications. Promise-based asynchronous loading and control flow. Can support any types of files, just create custom loader for your custom files.
Installation:
// NPM npm install loaderjs
Usage
For global window:
For Webpack or Browserify:
// Importvar LoaderJS = ;// Start loadingLoaderJS;
LoaderJS.load(resources [, callback]) -> Promise
To start loading resources, just call LoaderJS.load(resource, callback)
, where resource is a 2-dimensional array of possible items, and optional callback function with parameters function(err, data){}
. Returns Promise
.
The resource collection must be a 2-Dimensional array.
- 1st level is
SEQUENCE
loading. Waits for the preceding element to finish. - 2nd level is
PARALLEL
loading. Does not wait, loads immediately.
The items can be.
- String
url
(like value of src attribute) - Promise
- Promise's
resolver
function -function(resolve, reject) {...}
- Object with
src
andthen
property -{ src: 'file.js', then: function() {...} }
- Any falsy value, which will auto resolve -
null or undefined or etc.
The callback function is triggered when loading is completely done or loader encounters error while loading.
- Check the
err
to see the status result - The
data
argument an array that contains the data passed by each loaders
LoaderJS currently contains predefined loaders for file JS, CSS, HTML (WebComponent). You can always create your own loaders to suits your needs.
Example Code:
var resA = ;// dummy-scriptA will always finish & execute first, than dummy-scriptB.resA;//dummy-img will load along with dummy-scriptA.resA;// A promiseresA// A promise resolverresA// ObjectresA var resB = ;// dummy-scriptB might finish last after dummy-css. Parallel loadingresB;// dummy-css might finish first than dummy-scriptB. Parallel loadingresB; var resC = 'dummy/dummy-480x270-FairyLights.jpg'; // Start loading resourcesLoaderJS;
LoaderJS.loadOne(resource)
Loads a single resource. Returns Promise
.
LoaderJS.loadMany(resources)
Loads multiple resources in parallel (1-dim array only). Returns Promise
.
Customize
To add custom loaders, just call LoaderJS.addLoader(loader)
where loader is an object must contain a property "ext" to associate the loader to a file(s).
There are 2 main types of custom loader:
- Loader that uses element to load files. (eg. js, css, html)
- Loader that does not use element to load files. (eg. jpg, png, gif, etc...)
Type 1: Load with element
// Javascript LoaderLoaderJS; // Stylesheet LoaderLoaderJS;
Type 2: Load without element. Add a property "custom" with function value.
// Custom LoaderLoaderJS;
Additionally, you can link more file extensions to existing loader.
LoaderJS;
More...
Progress Callback
You can also add 3rd argument to LoadJS.load(res, cb, progress)
which enables to keep track of the progress. The callback will pass the percentage of the loading progress.
License
MIT