Skip to content

Commit

Permalink
only "track" changes to the query string of a data-navigate-track asset
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed Aug 8, 2023
1 parent df92140 commit 04ddd68
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions packages/navigate/src/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ function prepNewBodyScriptTagsToRun(newBody, oldBodyScriptTagHashes) {
}

function mergeNewHead(newHead) {
let headChildrenHtmlLookup = Array.from(document.head.children).map(i => i.outerHTML)
let children = Array.from(document.head.children)
let headChildrenHtmlLookup = children.map(i => i.outerHTML)

// Only add scripts and styles that aren't already loaded on the page.
let garbageCollector = document.createDocumentFragment()
Expand All @@ -71,9 +72,9 @@ function mergeNewHead(newHead) {
if (isAsset(child)) {
if (! headChildrenHtmlLookup.includes(child.outerHTML)) {
if (isTracked(child)) {
setTimeout(() => window.location.reload())

return
if (ifTheQueryStringChangedSinceLastRequest(child, children)) {
setTimeout(() => window.location.reload())
}
}

if (isScript(child)) {
Expand Down Expand Up @@ -117,6 +118,25 @@ function isTracked(el) {
return el.hasAttribute('data-navigate-track')
}

function ifTheQueryStringChangedSinceLastRequest(el, currentHeadChildren) {
let [uri, queryString] = extractUriAndQueryString(el)

return currentHeadChildren.some(child => {
if (! isTracked(child)) return false

let [currentUri, currentQueryString] = extractUriAndQueryString(child)

// Only consider a data-navigate-track element changed if the query string has changed (not the URI)...
if (currentUri === uri && queryString !== currentQueryString) return true
})
}

function extractUriAndQueryString(el) {
let url = isScript(el) ? el.src : el.href

return url.split('?')
}

function isAsset(el) {
return (el.tagName.toLowerCase() === 'link' && el.getAttribute('rel').toLowerCase() === 'stylesheet')
|| el.tagName.toLowerCase() === 'style'
Expand Down

0 comments on commit 04ddd68

Please sign in to comment.