Skip to content

Commit

Permalink
fix(client): only update head if needed (#3017)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Sep 25, 2023
1 parent a291103 commit f2fc3dc
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions src/client/app/composables/head.ts
Expand Up @@ -8,7 +8,7 @@ import {
import type { Route } from '../router'

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

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

managedHeadTags.forEach((el) => document.head.removeChild(el))
managedHeadTags = []
newTags.forEach((headConfig) => {
const el = createHeadElement(headConfig)
document.head.appendChild(el)
managedHeadTags.push(el)
const newElements: (HTMLElement | undefined)[] =
newTags.map(createHeadElement)

managedHeadElements.forEach((oldEl, oldIndex) => {
const matchedIndex = newElements.findIndex(
(newEl) => newEl?.isEqualNode(oldEl ?? null)
)
if (matchedIndex !== -1) {
delete newElements[matchedIndex]
} else {
oldEl?.remove()
delete managedHeadElements[oldIndex]
}
})

newElements.forEach((el) => el && document.head.appendChild(el))
managedHeadElements = [...managedHeadElements, ...newElements].filter(
Boolean
)
}

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

// update title and description
document.title = createTitle(siteData, pageData)
const title = createTitle(siteData, pageData)
if (title !== document.title) {
document.title = title
}

const description = pageDescription || siteData.description
let metaDescriptionElement = document.querySelector(
`meta[name=description]`
)
if (metaDescriptionElement) {
metaDescriptionElement.setAttribute('content', description)
if (metaDescriptionElement.getAttribute('content') !== description) {
metaDescriptionElement.setAttribute('content', description)
}
} else {
createHeadElement(['meta', { name: 'description', content: description }])
}
Expand Down

0 comments on commit f2fc3dc

Please sign in to comment.