Skip to content

Commit

Permalink
Add optional id attribute to ScriptDescriptor
Browse files Browse the repository at this point in the history
This is to allow for later referencing of external scripts by ID if
desired
  • Loading branch information
mnemitz committed Aug 16, 2024
1 parent ad28fea commit ed859e9
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/react/external-scripts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export type ScriptDescriptor = {
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type
*/
type?: ScriptType;
/**
* Optional element ID. Use only if the script element needs to be explicitly referenced later.
*/
id?: string;
};

export type ExternalScriptsFunction<Loader = unknown> = (
Expand Down Expand Up @@ -168,6 +172,7 @@ export function ExternalScript({
referrerPolicy,
noModule,
nonce,
id,
}: ScriptDescriptor) {
let isHydrated = useHydrated();
let startsHydrated = React.useRef(isHydrated);
Expand All @@ -187,13 +192,14 @@ export function ExternalScript({
referrerPolicy,
noModule,
nonce,
id,
};

for (let [key, value] of Object.entries(attributes)) {
if (value) $script.setAttribute(key, value.toString());
}

document.body.append($script);
document.body.appendChild($script);

return () => $script.remove();
}, [
Expand All @@ -207,6 +213,7 @@ export function ExternalScript({
referrerPolicy,
src,
type,
id,
]);

if (startsHydrated.current && isHydrated) return null;
Expand All @@ -227,6 +234,7 @@ export function ExternalScript({
/>
)}
<script
id={id}
src={src}
defer={defer}
async={async}
Expand Down

0 comments on commit ed859e9

Please sign in to comment.