1.0.0 • Published 5 years ago

command-queue-module v1.0.0

Weekly downloads
275
License
MIT
Repository
-
Last release
5 years ago

Command Queue Module

License: MIT Minified Size

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 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()

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

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