Static Assets loader
npm install assets-dynamic-importSimple way to dynamicly import some external assets in the runtime.
``shell`
npm install --save assets-dynamic-import
`js
import { importScript } from 'assets-dynamic-import';
const processSomeData = async data => {
const { someFnFromMyLib } = await importScript(
'//some.path.to/script.js',
() => global.someGlobalLibraryName
);
return someFnFromMyLib(data);
}
`
`ts
import { importScript, importStyle } from 'assets-dynamic-import';
export interface Recurly {
token(form: HTMLFormElement, cb: (err: Error | null, token: string) => void): void;
}
export default () => Promise.all([
() => importScript('https://js.recurly.com/v4/recurly.js'),
() => importStyle('https://js.recurly.com/v4/recurly.css'),
])
.then(() => {
const recurly = (window as any).recurly as Recurly;
return {
token: (form: HTMLFormElement): Promise
(resolve, reject) => recurly.token(form, (err: Error | null, token: string) => (
err == null ? resolve(token) : reject(err)
)
)),
};
});
`
The main idea of the library to provide users with minimal tool set that allows to
work with external (to application bundle) assets.
The library is developed considering following use cases:
1. to use extrnal libraries in single-page appliction preventing excess loading of
not-used of them for major of pages (aka
recurly,
stripe,
pdf.js
etc.)
2. integrate separetelly deployed SPA's to one large single page application.
`js
import React from 'react';
import { importScript } from 'assets-dynamic-import';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { CDN } from './config';
const ViewerApplication = React.lazy(
() => importScript(
${CDN}/viewer.bundle.js,
() => global.viewerLib.default,
)
);
const MyAccountApplication = React.lazy(
() => importScript(
${CDN}/myaccount.bundle.js,
() => global.accountLib.default,
)
);
const App = () => (
);
export default App;
`
The library exports the following functions:
| Function | Target | Child | Cache | Description |
|:--------------:|:------:|:--------:|:-----:|:----------------------------------------------------------|
| importScript | body | script | yes | Imports javascript-assets and caches such imports |body
| appendScript | | script | no | Creates a script-node and appends it to the document body that initiats resourse loading |head
| importStyle | | link | yes | Imports CSS-assets and caches such imports |head
| appendStyle | | link | no | Creates a link-node and appends it to the document head that initiats resource loading |onload
| createElement | n/a | n/a | no | Creates DOMNode and assigns its properties |
| appendNodeAsync | any | any | no | Assigns and onerror event lesteners of the Child and appends it to the Target |
| cacheAll | n/a | n/a | n/a | Memoization function decorator |
----
Creates