dynamic-import-assets
v1.1.0
Published
Dynamic Import Assets like JavaScript and CSS.
Downloads
33
Readme
dynamic-import-assets
Dynamic Import Assets like JavaScript and CSS.
Feature
- Dynamic load JavaScript and CSS from URL
- Support Promises
- Work with ES modules registry like UNPKG and Pika CDN
Install
Install with npm:
npm install dynamic-import-assets
Usage
Provide these APIs
dynamicImportScript
: Load JavaScript Script and resolve with loaded<script>
dynamicImportCSS
: Load CSS Script and resolve with<link>
export declare type Loader<T extends HTMLElement> = (url: string) => Promise<T>;
export declare function createDynamicImportAssetsLoader<T extends HTMLElement>(loader: Loader<T>): (url: string) => Promise<T>;
export declare const dynamicImportScript: (url: string) => Promise<HTMLScriptElement>;
export declare const dynamicImportCSS: (url: string) => Promise<HTMLLinkElement>;
Examples
For example, you want to load https://toast.evila.me/'s js and css using UNPKG, do following:
(async function main(){
const { dynamicImportCSS } = await import("https://unpkg.com/dynamic-import-assets@^1.0.0?module");
const { createToast } = await import("https://unpkg.com/@evillt/[email protected]?module");
// inject <link rel="stylesheet">
await dynamicImportCSS("https://unpkg.com/@evillt/[email protected]/dist/toast.min.css", { type: "css" });
// use toast after loaded
createToast("Hello world");
})();
Also support JavaScript as script loading:
(async function main(){
const { dynamicImportJS, dynamicImportCSS } = await import("https://unpkg.com/dynamic-import-assets@^1.0.0?module");
await Promise.all([
// inject <link rel="stylesheet">
dynamicImportCSS("https://unpkg.com/@evillt/[email protected]/dist/toast.min.css", { type: "css" }),
// inject <script>
dynamicImportJS("https://unpkg.com/@evillt/[email protected]", { type: "js" })
]);
// use toast after loaded
toast.createToast("Hello world");
})();
Changelog
See Releases page.
Running tests
Install devDependencies and Run npm test
:
npm test
Contributing
Pull requests and stars are always welcome.
For bugs and feature requests, please create an issue.
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
Author
License
MIT © azu