Skip to content

Instantly share code, notes, and snippets.

@songjiz
Forked from julianrubisch/prefetch_controller.js
Created February 2, 2023 14:25
Show Gist options
  • Save songjiz/0664b0030d1f6cfb4aea86fec5b7b398 to your computer and use it in GitHub Desktop.
Save songjiz/0664b0030d1f6cfb4aea86fec5b7b398 to your computer and use it in GitHub Desktop.
import { Controller } from "stimulus";
import { get } from "@rails/request.js";
import { PageSnapshot } from "@hotwired/turbo";
export default class extends Controller {
static values = { hoverTime: Number };
connect() {
this.element.addEventListener("mouseover", this.prefetch.bind(this));
this.element.addEventListener("touchstart", this.prefetch.bind(this));
}
async prefetch(e) {
if (this.prefetched) return;
const response = await get(this.url.toString());
if (response.ok) {
const html = await response.html;
const snapshot = snapshotFromHTML(html);
Turbo.navigator.view.snapshotCache.put(this.url, snapshot);
}
}
get prefetched() {
return (
location.href === this.url ||
Turbo.navigator.view.snapshotCache.has(this.url)
);
}
get url() {
this._url =
this._url || new URL(this.element.getAttribute("href"), document.baseURI);
return this._url;
}
get hoverTime() {
return this.hoverTimeValue || 300;
}
}
const snapshotFromHTML = (html) => PageSnapshot.fromHTMLString(html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment