Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Last active March 21, 2018 08:43
Show Gist options
  • Save c7x43t/a7b54c0881329fae6b66a468ca1bf291 to your computer and use it in GitHub Desktop.
Save c7x43t/a7b54c0881329fae6b66a468ca1bf291 to your computer and use it in GitHub Desktop.
var kryoPrefetch = {
_init: function() {
debug = true;
store = {
clicked: undefined,
mouseDown: false,
targetMatch: false,
pending: false,
href: ""
};
document.addEventListener("mousedown", e => {
let target = e.target;
let parent = target.parentElement;
let child = target.querySelector("a");
store.clicked = target;
if (child !== null) {
target = child;
} else if (parent.tagName === "A") target = parent;
if (target.tagName === "A") {
store.href = target.href;
store.mouseDown = true;
let node = document.createElement('div');
node.innerHTML = `<link rel=prefetch href="${target.href}" onload="kryoPrefetch.complete()" />`;
document.querySelector('head').appendChild(node.childNodes[0]);
store.pending = true;
e.preventDefault();
}
});
document.addEventListener("mouseup", e => {
store.targetMatch = store.clicked === e.target;
if (!store.pending) {
if (store.targetMatch) {
window.location.href = store.href;
if (debug) console.log(store);
}
}
});
document.addEventListener("click", e => {
if (store.mouseDown) e.preventDefault();
store.mouseDown = false;
});
return store;
}(),
complete: function() {
store.pending = false;
if (!store.mouseDown) {
if (store.targetMatch) {
window.location.href = store.href;
if (debug) console.log(store);
}
}
}
}
var kryoPrefetch = {
_init: function() {
$$("a")
.on("mousedown",e=>{
store.mouseDown = true;
$$("head").append('<link rel=prefetch href="'+e.href+'" onload="kryoPrefetch.complete()" />');
store.pending = true;
e.preventDefault();
})
.on("mouseup",e=>{
if (!store.pending) window.location.href = store.href;
})
.on("click",e=>{
if (store.mouseDown) e.preventDefault();
store.mouseDown = false;
})
}(),
complete: function() {
store.pending = false;
if (!store.mouseDown) window.location.href = store.href;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment