@@ -4,6 +4,32 @@ import type { HeadConfig, VuepressSSRContext } from '@vuepress/shared'
4
4
import { usePageHead } from './pageHead'
5
5
import { usePageLang } from './pageLang'
6
6
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
+
7
33
/**
8
34
* Create head tag from head config
9
35
*/
@@ -57,32 +83,41 @@ export const useUpdateHead = (): void => {
57
83
return
58
84
}
59
85
60
- // current tag elements that generated by this function
61
- const currentTags = ref < HTMLElement [ ] > ( [ ] )
86
+ const headTags = ref < HTMLElement [ ] > ( [ ] )
62
87
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
+ }
67
97
98
+ // update html lang attribute and head tags to DOM
99
+ const updateHead = ( ) : void => {
68
100
document . documentElement . lang = lang . value
69
101
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 )
73
105
}
74
106
} )
75
- currentTags . value . splice ( 0 , currentTags . value . length )
107
+ headTags . value . splice ( 0 , headTags . value . length )
76
108
77
109
head . value . forEach ( ( item ) => {
78
110
const tag = createHeadTag ( item )
79
111
if ( tag !== null ) {
80
112
document . head . appendChild ( tag )
81
- currentTags . value . push ( tag )
113
+ headTags . value . push ( tag )
82
114
}
83
115
} )
84
116
}
85
117
86
- onMounted ( ( ) => updateHead ( ) )
87
- watch ( head , ( ) => updateHead ( ) )
118
+ onMounted ( ( ) => {
119
+ loadHead ( )
120
+ updateHead ( )
121
+ watch ( [ head , lang ] , ( ) => updateHead ( ) )
122
+ } )
88
123
}
0 commit comments