Skip to content

Commit

Permalink
fix(useScript): allow load() to be called again once remove() is …
Browse files Browse the repository at this point in the history
…called
  • Loading branch information
harlan-zw committed Dec 8, 2024
1 parent dcc1964 commit 6a9b4e1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/unhead/src/composables/useScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export function useScript<T extends Record<symbol | string, any> = Record<symbol
script._triggerPromises = [] // clear any pending promises
if (script.entry) {
script.entry.dispose()
script.entry = undefined
syncStatus('removed')
delete head._scripts?.[id]
return true
Expand Down
28 changes: 28 additions & 0 deletions test/unhead/dom/useScript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,32 @@ describe('dom useScript', () => {

expect(await instance.proxy.test('hello-world')).toEqual('hello-world')
})
it('remove & re-add', async () => {
useDOMHead()

const instance = useScript<{ test: (foo: string) => void }>({
src: 'https://cdn.example.com/script.js',
})

let dom = await useDelayedSerializedDom()
expect(dom.split('\n').filter(l => l.trim().startsWith('<script'))).toMatchInlineSnapshot(`
[
"<script data-onload="" data-onerror="" defer="" fetchpriority="low" crossorigin="anonymous" referrerpolicy="no-referrer" src="https://cdn.example.com/script.js" data-hid="c5c65b0"></script></head>",
]
`)
instance.remove()
// wait
await new Promise((r) => setTimeout(r, 100))
dom = await useDelayedSerializedDom()
expect(dom.split('\n').filter(l => l.trim().startsWith('<script'))).toMatchInlineSnapshot(`[]`)
// reload
instance.load()
await new Promise((r) => setTimeout(r, 100))
dom = await useDelayedSerializedDom()
expect(dom.split('\n').filter(l => l.trim().startsWith('<script'))).toMatchInlineSnapshot(`
[
"<script data-onload="" data-onerror="" defer="" fetchpriority="low" crossorigin="anonymous" referrerpolicy="no-referrer" src="https://cdn.example.com/script.js" data-hid="c5c65b0"></script></head>",
]
`)
})
})

0 comments on commit 6a9b4e1

Please sign in to comment.