Skip to content

Commit f2fc3dc

Browse files
authoredSep 25, 2023
fix(client): only update head if needed (#3017)
1 parent a291103 commit f2fc3dc

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed
 

‎src/client/app/composables/head.ts

+26-9
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import type { Route } from '../router'
99

1010
export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
11-
let managedHeadTags: HTMLElement[] = []
11+
let managedHeadElements: (HTMLElement | undefined)[] = []
1212
let isFirstUpdate = true
1313

1414
const updateHeadTags = (newTags: HeadConfig[]) => {
@@ -19,13 +19,25 @@ export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
1919
return
2020
}
2121

22-
managedHeadTags.forEach((el) => document.head.removeChild(el))
23-
managedHeadTags = []
24-
newTags.forEach((headConfig) => {
25-
const el = createHeadElement(headConfig)
26-
document.head.appendChild(el)
27-
managedHeadTags.push(el)
22+
const newElements: (HTMLElement | undefined)[] =
23+
newTags.map(createHeadElement)
24+
25+
managedHeadElements.forEach((oldEl, oldIndex) => {
26+
const matchedIndex = newElements.findIndex(
27+
(newEl) => newEl?.isEqualNode(oldEl ?? null)
28+
)
29+
if (matchedIndex !== -1) {
30+
delete newElements[matchedIndex]
31+
} else {
32+
oldEl?.remove()
33+
delete managedHeadElements[oldIndex]
34+
}
2835
})
36+
37+
newElements.forEach((el) => el && document.head.appendChild(el))
38+
managedHeadElements = [...managedHeadElements, ...newElements].filter(
39+
Boolean
40+
)
2941
}
3042

3143
watchEffect(() => {
@@ -35,14 +47,19 @@ export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
3547
const frontmatterHead = (pageData && pageData.frontmatter.head) || []
3648

3749
// update title and description
38-
document.title = createTitle(siteData, pageData)
50+
const title = createTitle(siteData, pageData)
51+
if (title !== document.title) {
52+
document.title = title
53+
}
3954

4055
const description = pageDescription || siteData.description
4156
let metaDescriptionElement = document.querySelector(
4257
`meta[name=description]`
4358
)
4459
if (metaDescriptionElement) {
45-
metaDescriptionElement.setAttribute('content', description)
60+
if (metaDescriptionElement.getAttribute('content') !== description) {
61+
metaDescriptionElement.setAttribute('content', description)
62+
}
4663
} else {
4764
createHeadElement(['meta', { name: 'description', content: description }])
4865
}

0 commit comments

Comments
 (0)
Please sign in to comment.