1.2.0 • Published 3 years ago

@pandasekh/dynamic-script-loader v1.2.0

Weekly downloads
5
License
MIT
Repository
github
Last release
3 years ago

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