mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-20 06:15:15 +00:00
add client-side preloading logic, move router into runtime module
This commit is contained in:
25
runtime/router.js
Normal file
25
runtime/router.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
const router = {
|
||||||
|
init(callback) {
|
||||||
|
console.log('initing');
|
||||||
|
window.addEventListener('click', event => {
|
||||||
|
let a = event.target;
|
||||||
|
while (a && a.nodeName !== 'A') a = a.parentNode;
|
||||||
|
if (!a) return;
|
||||||
|
|
||||||
|
if (callback(new URL(a.href))) {
|
||||||
|
event.preventDefault();
|
||||||
|
history.pushState({}, '', a.href);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('popstate', event => {
|
||||||
|
callback(window.location);
|
||||||
|
});
|
||||||
|
|
||||||
|
callback(window.location);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.router = router;
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -1,22 +1,9 @@
|
|||||||
window.addEventListener('click', event => {
|
import router from 'sapper/runtime/router.js';
|
||||||
let a = event.target;
|
|
||||||
while (a && a.nodeName !== 'A') a = a.parentNode;
|
|
||||||
if (!a) return;
|
|
||||||
|
|
||||||
if (navigate(new URL(a.href))) {
|
|
||||||
event.preventDefault();
|
|
||||||
history.pushState({}, '', a.href);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener('popstate', event => {
|
|
||||||
navigate(window.location);
|
|
||||||
});
|
|
||||||
|
|
||||||
const target = document.querySelector('__selector__');
|
const target = document.querySelector('__selector__');
|
||||||
let component;
|
let component;
|
||||||
|
|
||||||
function navigate(url) {
|
router.init(url => {
|
||||||
if (url.origin !== window.location.origin) return;
|
if (url.origin !== window.location.origin) return;
|
||||||
|
|
||||||
let match;
|
let match;
|
||||||
@@ -24,22 +11,26 @@ function navigate(url) {
|
|||||||
const query = {};
|
const query = {};
|
||||||
|
|
||||||
function render(mod) {
|
function render(mod) {
|
||||||
if (component) {
|
const route = { query, params };
|
||||||
component.destroy();
|
|
||||||
} else {
|
|
||||||
target.innerHTML = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
component = new mod.default({
|
Promise.resolve(
|
||||||
target,
|
mod.default.preload ? mod.default.preload(route) : {}
|
||||||
data: { query, params },
|
).then(preloaded => {
|
||||||
hydrate: !!component
|
if (component) {
|
||||||
|
component.destroy();
|
||||||
|
} else {
|
||||||
|
target.innerHTML = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
component = new mod.default({
|
||||||
|
target,
|
||||||
|
data: Object.assign(route, preloaded),
|
||||||
|
hydrate: !!component
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ROUTES
|
// ROUTES
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
});
|
||||||
|
|
||||||
navigate(window.location);
|
|
||||||
Reference in New Issue
Block a user