Skip to Content
ohooks

useScript

Dynamically loads an external <script> tag, deduplicating across components and tracking its status.

Loading preview...

The useScript hook injects an external <script> tag into document.body (or attaches to an existing tag with the same src), deduplicates concurrent requests across multiple mounted components, and returns the current loading status ('idle', 'loading', 'ready', or 'error').

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useScript.json

Usage

Examples

Rendering a Widget Once the Script is 'ready'

Check status === "ready" before initializing or rendering components that depend on the global script.

Conditional Loading and Cleanup on Unmount

Pass null (or shouldPreventLoad: true) to defer loading until needed, and removeOnUnmount: true to remove the <script> tag when the last consumer unmounts.

API Reference

UseScriptOptions

Configuration options for script attributes, conditional loading, and unmount cleanup.

Property
Specification
shouldPreventLoad?
uniondefault:false
Prevent the script from loading while true
removeOnUnmount?
uniondefault:false
Remove the <script> element when the last consumer unmounts
id?
string
Optional id attribute for the <script> tag.
async?
uniondefault:true
Set the async attribute on the <script> tag
defer?
uniondefault:false
Set the defer attribute on the <script> tag
crossOrigin?
union
CORS setting for the <script> element.
integrity?
string
Subresource Integrity (integrity) hash.
type?
string
Script type attribute (e.g. 'module').
noModule?
union
Set the noModule attribute on the <script> tag.
referrerPolicy?
union
Referrer policy for fetching the script.