command-queue-module
Version:
Create command queue proxies for modules
88 lines (54 loc) • 2.82 kB
Markdown
# Command Queue Module
[![License: MIT][mit-img]][mit-url]
[![Minified Size][size-img]][size-url]
Create simple [command queue] proxies for modules.
## Motivation
You can boost the initial load performance of a page by requesting some non-crucial scripts asynchronously, but at the same time you might need to queue some calls to these libraries early on.
A common example is event / error tracking - it's not necessary to start _sending_ events right after load, but it's beneficial to start _collecting_ them as early as possible.
This project enables you to create proxy module **for any library** with the **exact same API** as the original, but the method calls are stored as [commands][wiki-command] and invoked only after the actual implementation is loaded.
## API
### `createCommandQueueModule(methodNames, loadCallback)`
#### `methodNames`
Type: `Array<string>`
Array of method names that will be proxied by the command queue. Other methods will not be available neither before or after load.
#### `loadCallback`
Type: `(onLoad: (actualModule) => void) => void`
Callback called right after calling `createCommandQueueModule`. It should accept `onLoad` function as it's only argument.
`onLoad` should be called with the actual module object when it's available.
## Examples
### Dynamic `import()`
```js
const createCommandQueueModule = require('command-queue-module');
const myTrackingLibrary = createCommandQueueModule(['trackEvent'], (onLoad) => {
import('my-tracking-library').then(onLoad);
}));
// Works no matter if library is already loaded or not
myTrackingLibrary.trackEvent('Hello world');
```
### Dynamically inserted `<script>` tag
```js
const createCommandQueueModule = require('command-queue-module');
const myTrackingLibrary = createCommandQueueModule(['trackEvent'], (onLoad) => {
const script = document.createElement('script');
script.src = 'https://example.org/my-tracking-library.umd.js';
script.onload = () => {
onLoad(window.MyTrackingLibrary)
};
document.body.append(script);
}));
// Works no matter if library is already loaded or not
myTrackingLibrary.trackEvent('Hello world');
```
## Prior art
- [lazy-async] is a much more complex implementation with similar API. Additional features cause the script to be 20x larger than this one.
## License
[MIT](./LICENSE)
<!-- badges -->
[mit-img]: https://img.shields.io/badge/License-MIT-blue.svg
[mit-url]: https://opensource.org/licenses/MIT
[size-img]: https://img.shields.io/github/size/brainly/error-queue/index.min.js.svg?color=blue&label=minified%20size
[size-url]: ./index.min.js
<!-- links -->
[command queue]: https://en.wikipedia.org/wiki/Command_queue
[wiki-command]: https://en.wikipedia.org/wiki/Command_pattern
[lazy-async]: https://github.com/bendrucker/lazy-async