Skip to content

Repository files navigation

@dschz/load-script

Licensenpm versionBundle SizeJSRCI

A lightweight utility for safely loading external scripts in the browser. Fully typed, SSR-aware, framework-agnostic, and caching-safe — ideal for modern web apps and libraries.

✅ Features

  • 📆 Small and framework-agnostic
  • 📑 Fully typed with TypeScript for autocompletion and safety
  • 🚫 Prevents duplicate script injection via internal cache
  • 🛡️ Safe to import and use in SSR and non-browser environments

📦 Installation

npm install @dschz/load-script
pnpm install @dschz/load-script
yarn install @dschz/load-script
bun install @dschz/load-script

🔧 Usage

import{loadScript}from"@dschz/load-script";awaitloadScript("https://example.com/library.js",{async: true,type: "text/javascript",});

🧠 API

loadScript(src, options?, container?)

Loads an external script dynamically and returns a Promise<HTMLScriptElement>.

Parameters:

NameTypeDescription
srcstringScript URL (required)
optionsLoadScriptOptionsloadScript options (e.g. async, type)
containerHTMLElementHTML element to append <script /> to (default: document.head)

📝 Notes

  • Scripts are cached by src. If innerHTML or textContent is set, the script will not be cached.
  • A nil (undefined/null) container value will append the script to document.head.
  • Cleanup is not automatic — script elements remain in the DOM
  • ❄️ SSR-safe: The function will reject gracefully when called in server environments without crashing. No DOM APIs are accessed until the environment is confirmed to be browser-based.

💬 Feedback & Contributions

Feel free to open issues or submit pull requests. PRs are welcome!

About

Dynamically load scripts in the browser with caching.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages