From ed859e9e1960a776e12a47072cd218a855e05dbb Mon Sep 17 00:00:00 2001 From: Matt Nemitz Date: Fri, 16 Aug 2024 11:01:28 +0100 Subject: [PATCH] Add optional `id` attribute to `ScriptDescriptor` This is to allow for later referencing of external scripts by ID if desired --- src/react/external-scripts.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/react/external-scripts.tsx b/src/react/external-scripts.tsx index 73e8b48..b686c8a 100644 --- a/src/react/external-scripts.tsx +++ b/src/react/external-scripts.tsx @@ -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 = ( @@ -168,6 +172,7 @@ export function ExternalScript({ referrerPolicy, noModule, nonce, + id, }: ScriptDescriptor) { let isHydrated = useHydrated(); let startsHydrated = React.useRef(isHydrated); @@ -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(); }, [ @@ -207,6 +213,7 @@ export function ExternalScript({ referrerPolicy, src, type, + id, ]); if (startsHydrated.current && isHydrated) return null; @@ -227,6 +234,7 @@ export function ExternalScript({ /> )}