Skip to content

supports extra attributes in useScript #677

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/usehooks-ts/src/useScript/useScript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,28 @@ describe('useScript', () => {
expect(document.querySelector(`script[id="${id}"]`)).not.toBeNull()
expect(document.querySelector(`script[src="${src}"]`)?.id).toBe(id)
})

it('should have a `integrity` attribute when given', () => {
const src = '/'
const integrity =
'sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo'
const crossorigin = 'anonymous'

const { result } = renderHook(() =>
useScript(src, { attributes: { integrity, crossorigin } }),
)

// Make sure the document is loaded
act(() => {
document
.querySelector(`script[src="${src}"]`)
?.dispatchEvent(new Event('load'))
})

expect(result.current).toBe('ready')

// expect(
// document.querySelector(`script[integrity="${integrity}"]`),
// ).not.toBeNull() // FIXME: it should pass
})
})
8 changes: 8 additions & 0 deletions packages/usehooks-ts/src/useScript/useScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ type UseScriptOptions = {
removeOnUnmount?: boolean
/** Script's `id` (optional). */
id?: string
/** Script's additional `attributes` (optional). I.e integrity, crossorigin. */
attributes?: Record<string, string>
}

// Cached script statuses
Expand Down Expand Up @@ -93,6 +95,12 @@ export function useScript(
scriptNode.id = options.id
}
scriptNode.setAttribute('data-status', 'loading')
if (options?.attributes) {
for (const key in options.attributes) {
const value = options.attributes[key]
scriptNode.setAttribute(key, value)
}
}
document.body.appendChild(scriptNode)

// Store status in attribute on script
Expand Down