Skip to content

Commit

Permalink
fix(client): handle head orphans added in initial load (#3474)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Jan 19, 2024
1 parent 9510cd7 commit 5e2d853
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/client/app/composables/head.ts
Expand Up @@ -8,14 +8,24 @@ import {
import type { Route } from '../router'

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

const updateHeadTags = (newTags: HeadConfig[]) => {
if (import.meta.env.PROD && isFirstUpdate) {
// in production, the initial meta tags are already pre-rendered so we
// skip the first update.
isFirstUpdate = false
newTags.forEach((tag) => {
const selector = toSelector(tag[0], tag[1])
const headEl = createHeadElement(tag)
;[...document.querySelectorAll(selector)].some((el) => {
if (el.isEqualNode(headEl)) {
managedHeadElements.push(el as HTMLElement)
return true
}
})
})
return
}

Expand Down Expand Up @@ -96,3 +106,9 @@ function isMetaDescription(headConfig: HeadConfig) {
function filterOutHeadDescription(head: HeadConfig[]) {
return head.filter((h) => !isMetaDescription(h))
}

function toSelector(tag: string, attrs: Record<string, string>) {
return `${tag}${Object.keys(attrs)
.map((key) => `[${key}="${attrs[key].replace(/(["'\\])/g, '\\$1')}"]`)
.join('')}`
}

0 comments on commit 5e2d853

Please sign in to comment.