diff --git a/index.d.ts b/index.d.ts index db01dc2..995acd3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -228,6 +228,7 @@ declare module "@uidotdev/usehooks" { src: string, options?: { removeOnUnmount?: boolean; + customAttributes?: Record; } ): "unknown" | "loading" | "ready" | "error"; diff --git a/index.js b/index.js index f6e4fe2..b4a191b 100644 --- a/index.js +++ b/index.js @@ -1112,6 +1112,10 @@ export function useScript(src, options = {}) { script.src = src; script.async = true; script.setAttribute("data-status", "loading"); + const customAttributes = optionsRef.current?.customAttributes ?? {}; + for(const [key, value] in Object.entries(customAttributes)) { + script.setAttribute(key, value); + } document.body.appendChild(script); const handleScriptLoad = () => { diff --git a/usehooks.com/src/content/hooks/useScript.mdx b/usehooks.com/src/content/hooks/useScript.mdx index 7a6d81a..8fe1557 100644 --- a/usehooks.com/src/content/hooks/useScript.mdx +++ b/usehooks.com/src/content/hooks/useScript.mdx @@ -29,7 +29,7 @@ import StaticCodeContainer from "../../components/StaticCodeContainer.astro"; | Name | Type | Description | | ---------------- | ------ | ----------- | | src | string | This is the URL source of the script to be loaded. | - | options | object | This is an optional configuration object provided when calling `useScript`. It currently accepts one property `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount. | + | options | object | This is an optional configuration object provided when calling `useScript`. It currently accepts two optional properties: `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount, and `customAttributes` which is an object of custom string attributes that will be added to the script tag, this can be useful for specifying things like license keys in `data-x` attributes. | ### Return Values @@ -58,6 +58,9 @@ export default function App() { `https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js`, { removeOnUnmount: false, + customAttributes: { + "data-uid": "useScript", + }, } );