Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vajahath/script-loader
Promise based script loading for browsers
https://github.com/vajahath/script-loader
Last synced: 13 days ago
JSON representation
Promise based script loading for browsers
- Host: GitHub
- URL: https://github.com/vajahath/script-loader
- Owner: vajahath
- License: mit
- Created: 2019-09-05T09:15:35.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-07-20T14:10:24.000Z (over 2 years ago)
- Last Synced: 2025-01-12T12:36:47.009Z (19 days ago)
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@vaju/script-loader
- Size: 12.7 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# script-loader
Promise based dynamic scripts loader for **browsers**.
## Why
- Load script files on demand _(for better page load performance)_.
- Duplication check _(skip loading if the same script is already loaded)_.
- Typescript ready.
- Promise ready.
- Support for [`defer`(default), `async`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Attributes).
- No dependencies, tiny (1.2 KB).## `defer` vs `async`
![loading diff](https://i.stack.imgur.com/wfL82.png)
## Install
```bash
npm i @vaju/script-loader
```## Usage
```ts
import { scriptLoader } from '@vaju/script-loader';// ...
await scriptLoader([
{ scr: 'https://cdn.firebase.com/libs/firebaseui/3.6.0/firebaseui.js' },// or optionally pass options
{
scr: 'https://cdn.firebase.com/libs/firebaseui/3.6.0/firebaseui.js',
opt: {
loadingMethod: 'defer', // default. OR use 'async' or null
type: 'text/javascript', // default
attrs: {}, // default
},
},
]);
```Results in appending the following script node to DOM (inside the `` or `` tag).
```html
```## APIs
```ts
import { scriptLoader } from '@vaju/script-loader';// ...
await scriptLoader(
dynamicScripts,
hostElement, // optional
document, // optional
);
```Where, **`dynamicScripts`** has the following form:
```ts
const dynamicScripts = [
{
src: 'script src url',
// optional opt
opt: {
loadingMethod: 'defer', // (default) script will have defer attribute
type: 'text/javascript', // (default)
attrs: {}, // optional map of attributes. Default is empty.
},
},
];
```Optional **hostElement** is an `HTMLElement` to which the `` tag is attached. Default is `<head> || <body>`
```ts
const hostElement = document.getElementsByTagName('head')[0];
```Optional `document` object. Default is `document`.
## v1 to v2 Migration Giude
The `{ "async": true }` property in the `opt` is now managed by the **optional** `loadingMethod` property in the `opt`.
The `loadingMethod` can have `defer`(default) or `async` values. [Learn more about these properties in MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Attributes).
## Licence
MIT © 2019 [Vajahath Ahmed](https://twitter.com/vajahath7)