Skip to content

Commit 15722c5

Browse files
committed
fix(client): load existing head tags on mounted
1 parent 6be78a2 commit 15722c5

File tree

1 file changed

+48
-13
lines changed

1 file changed

+48
-13
lines changed

packages/@vuepress/client/src/injections/updateHead.ts

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,32 @@ import type { HeadConfig, VuepressSSRContext } from '@vuepress/shared'
44
import { usePageHead } from './pageHead'
55
import { usePageLang } from './pageLang'
66

7+
/**
8+
* Query the matched head tag of head config
9+
*/
10+
export const queryHeadTag = ([
11+
tagName,
12+
attrs,
13+
content = '',
14+
]: HeadConfig): HTMLElement | null => {
15+
const attrsSelector = Object.entries(attrs).map(([key, value]) => {
16+
if (isString(value)) {
17+
return `[${key}="${value}"]`
18+
}
19+
20+
if (value === true) {
21+
return `[${key}]`
22+
}
23+
24+
return ''
25+
})
26+
27+
const selector = `head > ${tagName}${attrsSelector}`
28+
const tags = Array.from(document.querySelectorAll<HTMLElement>(selector))
29+
const matchedTag = tags.find((item) => item.innerText === content)
30+
return matchedTag || null
31+
}
32+
733
/**
834
* Create head tag from head config
935
*/
@@ -57,32 +83,41 @@ export const useUpdateHead = (): void => {
5783
return
5884
}
5985

60-
// current tag elements that generated by this function
61-
const currentTags = ref<HTMLElement[]>([])
86+
const headTags = ref<HTMLElement[]>([])
6287

63-
const updateHead = (): void => {
64-
if (!document) {
65-
return
66-
}
88+
// load current head tags from DOM
89+
const loadHead = (): void => {
90+
head.value.forEach((item) => {
91+
const tag = queryHeadTag(item)
92+
if (tag) {
93+
headTags.value.push(tag)
94+
}
95+
})
96+
}
6797

98+
// update html lang attribute and head tags to DOM
99+
const updateHead = (): void => {
68100
document.documentElement.lang = lang.value
69101

70-
currentTags.value.forEach((el) => {
71-
if (el.parentNode === document.head) {
72-
document.head.removeChild(el)
102+
headTags.value.forEach((item) => {
103+
if (item.parentNode === document.head) {
104+
document.head.removeChild(item)
73105
}
74106
})
75-
currentTags.value.splice(0, currentTags.value.length)
107+
headTags.value.splice(0, headTags.value.length)
76108

77109
head.value.forEach((item) => {
78110
const tag = createHeadTag(item)
79111
if (tag !== null) {
80112
document.head.appendChild(tag)
81-
currentTags.value.push(tag)
113+
headTags.value.push(tag)
82114
}
83115
})
84116
}
85117

86-
onMounted(() => updateHead())
87-
watch(head, () => updateHead())
118+
onMounted(() => {
119+
loadHead()
120+
updateHead()
121+
watch([head, lang], () => updateHead())
122+
})
88123
}

0 commit comments

Comments
 (0)