2.0.1 • Published 6 years ago
@vaju/script-loader v2.0.1
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. - No dependencies, tiny (1.2 KB).
defer vs async

Install
npm i @vaju/script-loaderUsage
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 <head> or <body> tag).
<script async type="text/javascript" src="https://.../firebaseui.js"></script>APIs
import { scriptLoader } from '@vaju/script-loader';
// ...
await scriptLoader(
dynamicScripts,
hostElement, // optional
document, // optional
);Where, dynamicScripts has the following form:
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 <script> tag is attached. Default is <head> || <body>
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.
Licence
MIT © 2019 Vajahath Ahmed