@pandasekh/dynamic-script-loader
v1.2.0
Published
Dynamically append and load scripts into your webpage only when they're needed.
Downloads
12
Maintainers
Readme
Dynamic Script Loader
🐼 Tiny (~300B) package to dynamically import Javascript files only when needed
Functionalities:
- 🤞 Promise based
- 🔎 Hashes the script source, preventing multiple identical imports
- ⚡️ Small, UMD file is about 300 bytes only!
Installation
Node:
npm i -S @pandasekh/dynamic-script-loader
Yarn:
yarn add @pandasekh/dynamic-script-loader
CDN
- Skypack
import loader from 'https://cdn.skypack.dev/@pandasekh/dynamic-script-loader';
- unpkg
<script src="https://unpkg.com/@pandasekh/dynamic-script-loader@latest">
Usage
// Import using JS Modules
import load from "@pandasekh/dynamic-script-loader"
// or using CommonJS
const load = require("@pandasekh/dynamic-script-loader")
// Using a CDN (Node not required)
import load from 'https://cdn.skypack.dev/@pandasekh/dynamic-script-loader';
// Then import a library only when needed
load("https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js")
// Promise based API
load("https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js").then(() => console.log("Loaded!"))
// Returns the generated DOM element
load("https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js").then(element => console.log(element.src))
Demo
Test this library on Codepen.
API
load
load(src: string) => Promise<HTMLScriptElement>
Default function, it will load a script asynchronously and return the HTMLScriptElement just created.
License
MIT License (c) 2021 Alessio Franceschi