fix(nuxt): speculation rules should be reactive (#9472)

This commit is contained in:
Daniel Roe 2022-12-05 10:46:13 +00:00 committed by GitHub
parent 1059b8c9a8
commit 5fe7c1c24d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,26 +4,31 @@ import { defineNuxtPlugin, useHead } from '#app'
export default defineNuxtPlugin((nuxtApp) => {
const externalURLs = ref(new Set<string>())
useHead({
script: [
() => ({
type: 'speculationrules',
innerHTML: JSON.stringify({
prefetch: [
{
source: 'list',
urls: [...externalURLs.value],
requires: ['anonymous-client-ip-when-cross-origin']
}
]
})
function generateRules () {
return {
type: 'speculationrules',
key: 'speculationrules',
innerHTML: JSON.stringify({
prefetch: [
{
source: 'list',
urls: [...externalURLs.value],
requires: ['anonymous-client-ip-when-cross-origin']
}
]
})
]
}
}
const head = useHead({
script: [generateRules()]
})
nuxtApp.hook('link:prefetch', (url) => {
const { protocol } = parseURL(url)
if (protocol && ['http:', 'https:'].includes(protocol)) {
externalURLs.value.add(url)
head?.patch({
script: [generateRules()]
})
}
})
})