2019-09-07 09:53:11 +03:00
|
|
|
module.exports = function pagesInit({ mainElmModule }) {
|
2019-09-15 02:22:13 +03:00
|
|
|
let prefetchedPages = [window.location.pathname];
|
|
|
|
|
2019-08-15 03:42:02 +03:00
|
|
|
document.addEventListener("DOMContentLoaded", function() {
|
|
|
|
let app = mainElmModule.init({
|
2019-09-07 09:53:11 +03:00
|
|
|
flags: {}
|
2019-08-15 03:42:02 +03:00
|
|
|
});
|
|
|
|
|
2019-09-15 02:36:32 +03:00
|
|
|
app.ports.toJsPort.subscribe(payload => {
|
|
|
|
if (payload.event === "page-changed") {
|
2019-09-15 02:22:13 +03:00
|
|
|
setupLinkPrefetching();
|
2019-09-15 02:36:32 +03:00
|
|
|
} else {
|
|
|
|
if (navigator.userAgent.indexOf("Headless") >= 0) {
|
|
|
|
headTags.forEach(headTag => {
|
|
|
|
appendTag(headTag);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
setupLinkPrefetching();
|
|
|
|
}
|
2019-08-15 03:42:02 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
document.dispatchEvent(new Event("prerender-trigger"));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2019-09-15 02:22:13 +03:00
|
|
|
function setupLinkPrefetching() {
|
2019-09-15 02:55:33 +03:00
|
|
|
setTimeout(setupLinkPrefetchingHelp, 1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
function setupLinkPrefetchingHelp() {
|
|
|
|
console.log("Setting up link hover prefetches...");
|
|
|
|
const links = document.querySelectorAll("a");
|
|
|
|
console.log("links", links);
|
|
|
|
links.forEach(link => {
|
|
|
|
link.addEventListener("mouseenter", function(event) {
|
|
|
|
if (event && event.target) {
|
|
|
|
prefetchIfNeeded(event.target);
|
|
|
|
} else {
|
|
|
|
console.log("Couldn't prefetch with event", event);
|
|
|
|
}
|
2019-09-15 02:22:13 +03:00
|
|
|
});
|
2019-09-15 02:55:33 +03:00
|
|
|
});
|
2019-09-15 02:22:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function prefetchIfNeeded(target) {
|
|
|
|
if (target.host === window.location.host) {
|
|
|
|
if (prefetchedPages.includes(target.pathname)) {
|
|
|
|
console.log("Already preloaded", event.target.href);
|
|
|
|
} else {
|
|
|
|
prefetchedPages.push(target.pathname);
|
|
|
|
console.log("Preloading...", target.pathname);
|
|
|
|
const link = document.createElement("link");
|
|
|
|
link.setAttribute("rel", "prefetch");
|
|
|
|
console.log(
|
|
|
|
origin,
|
|
|
|
" + ",
|
|
|
|
"content.txt",
|
|
|
|
" = ",
|
|
|
|
origin + target.pathname + "/content.txt"
|
|
|
|
);
|
|
|
|
link.setAttribute("href", origin + target.pathname + "/content.txt");
|
|
|
|
document.head.appendChild(link);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-15 03:42:02 +03:00
|
|
|
function appendTag(tagDetails) {
|
|
|
|
const meta = document.createElement(tagDetails.name);
|
|
|
|
tagDetails.attributes.forEach(([name, value]) => {
|
|
|
|
meta.setAttribute(name, value);
|
|
|
|
});
|
|
|
|
document.getElementsByTagName("head")[0].appendChild(meta);
|
|
|
|
}
|
|
|
|
};
|