({
attrs,
children,
}: {
attrs?: ScriptAttrs
children?: string
})
| 32 | } |
| 33 | |
| 34 | function Script({ |
| 35 | attrs, |
| 36 | children, |
| 37 | }: { |
| 38 | attrs?: ScriptAttrs |
| 39 | children?: string |
| 40 | }): JSX.Element | null { |
| 41 | const router = useRouter() |
| 42 | const dataScript = |
| 43 | typeof attrs?.type === 'string' && |
| 44 | attrs.type !== '' && |
| 45 | attrs.type !== 'text/javascript' && |
| 46 | attrs.type !== 'module' |
| 47 | |
| 48 | onMount(() => { |
| 49 | if (dataScript) return |
| 50 | |
| 51 | if (attrs?.src) { |
| 52 | const normSrc = (() => { |
| 53 | try { |
| 54 | const base = document.baseURI || window.location.href |
| 55 | return new URL(attrs.src, base).href |
| 56 | } catch { |
| 57 | return attrs.src |
| 58 | } |
| 59 | })() |
| 60 | const existingScript = Array.from( |
| 61 | document.querySelectorAll('script[src]'), |
| 62 | ).find((el) => (el as HTMLScriptElement).src === normSrc) |
| 63 | |
| 64 | if (existingScript) { |
| 65 | return |
| 66 | } |
| 67 | |
| 68 | const script = document.createElement('script') |
| 69 | |
| 70 | for (const [key, value] of Object.entries(attrs)) { |
| 71 | if (value !== undefined && value !== false) { |
| 72 | script.setAttribute( |
| 73 | key, |
| 74 | typeof value === 'boolean' ? '' : String(value), |
| 75 | ) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | document.head.appendChild(script) |
| 80 | |
| 81 | onCleanup(() => { |
| 82 | if (script.parentNode) { |
| 83 | script.parentNode.removeChild(script) |
| 84 | } |
| 85 | }) |
| 86 | } |
| 87 | |
| 88 | if (typeof children === 'string') { |
| 89 | const typeAttr = |
| 90 | typeof attrs?.type === 'string' ? attrs.type : 'text/javascript' |
| 91 | const nonceAttr = |
nothing calls this directly
no test coverage detected