unistar-async-script-loader
Asynchronous script loader to dynamicly load and destory arbitrary scripts.
Getting Started
install from https://www.npmjs.com/package/unistar-async-script-loader and use.
npm install unistar-async-script-loader
Usage
AsyncScriptLoader ; AsyncScriptLoader ;
The scripts will be appended to document.body.
API
/** * the API class * * the functions are divided into 2 modes: * script(), func(), wait() and destory() run in record mode. * they will simply push a task in the running queue of the LoadingChain, * and they does not perform the actural loading and destory task. * * run() runs in execute mode. * it will asynchronously execute the tasks in the running queue. * tasks in the queue are parallel executed, unless a wait() call is specified in the record mode. * no more API invocations to the LoadingChain can be performed after the run() method. */;
LICENSE
MIT.
Why I wrote this
Maybe sometimes you have to write a page which dynamicly load and execute some JS files. Which files are executed depends on user choice (geolocation, sales product, etc.). But dependency resolving in webpack is static, so when you write 'require' in your code, webpack will resolve it in compile time. This is not we want.
This code is inspired by LABjs. Since LABjs does not support commonjs and is hard to intergrate into webpack compilation, I rewrite the core code in typescript.
Moreover, SPAs are more and more popular these days, we'll have to do some cleanup when we 'switch pages' in SPA framework. So I added a 'destroyCallback' to 'destroy' the side effect of loading the script, you can do some cleanup in this callback.