Skip to content

Commit

Permalink
Add optional id attribute to ScriptDescriptor (#379)
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.

We're specifically using this functionality in our app to interact with
a third party script's globals only after the script has loaded.

Happy to discuss if you have any questions about this, or if there's a
better approach!
  • Loading branch information
mnemitz authored Sep 20, 2024
1 parent 6f58d0a commit 6d17f05
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 6d17f05

Please sign in to comment.