Skip to content

Commit

Permalink
LinkPrefetchObserver: replace dataset with getAttribute (#1148)
Browse files Browse the repository at this point in the history
First, import the `StreamMessage` module to utilize the `contentType`
instead of the hard-coded `"text/vnd.turbo-stream.html"` String.

Next, replace occurrences of [HTMLElement.dataset][] with the
`"data-"`-prefixed calls to [Element.getAttribute][] so that they are as
`grep`-able as their counterparts elsewhere in the codebase.

Finally, remove a `link` comparison conditional clause, since it's
repeated verbatim several lines prior to it.

[HTMLElement.dataset]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
[Element.getAttribute]: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  • Loading branch information
seanpdoyle authored Jan 31, 2024
1 parent 063d556 commit f81f9c2
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/observers/link_prefetch_observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
findClosestRecursively
} from "../util"

import { StreamMessage } from "../core/streams/stream_message"
import { FetchMethod, FetchRequest } from "../http/fetch_request"
import { prefetchCache, cacheTtl } from "../core/drive/prefetch_cache"

Expand Down Expand Up @@ -108,7 +109,7 @@ export class LinkPrefetchObserver {
}

if (link.hasAttribute("data-turbo-stream")) {
request.acceptResponseType("text/vnd.turbo-stream.html")
request.acceptResponseType(StreamMessage.contentType)
}
}

Expand All @@ -133,7 +134,7 @@ export class LinkPrefetchObserver {
#isPrefetchable(link) {
const href = link.getAttribute("href")

if (!href || href === "#" || link.dataset.turbo === "false" || link.dataset.turboPrefetch === "false") {
if (!href || href === "#" || link.getAttribute("data-turbo") === "false" || link.getAttribute("data-turbo-prefetch") === "false") {
return false
}

Expand All @@ -149,21 +150,18 @@ export class LinkPrefetchObserver {
return false
}

if (link.dataset.turboMethod && link.dataset.turboMethod !== "get") {
const turboMethod = link.getAttribute("data-turbo-method")
if (turboMethod && turboMethod !== "get") {
return false
}

if (targetsIframe(link)) {
return false
}

if (link.pathname + link.search === document.location.pathname + document.location.search) {
return false
}

const turboPrefetchParent = findClosestRecursively(link, "[data-turbo-prefetch]")

if (turboPrefetchParent && turboPrefetchParent.dataset.turboPrefetch === "false") {
if (turboPrefetchParent && turboPrefetchParent.getAttribute("data-turbo-prefetch") === "false") {
return false
}

Expand Down

0 comments on commit f81f9c2

Please sign in to comment.