Skip to main content
Deno 2 is finally here ๐ŸŽ‰๏ธ
Learn more

Dynamic Script Loader

Tests codecov npm bundle size

๐Ÿผ 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