From 7e2f5f8fb6bbfdf9289a7b35be2279659e27ef5f Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Sun, 4 Mar 2018 18:05:33 -0500 Subject: [PATCH] add preloadRoutes function - closes #160 --- src/runtime/index.ts | 15 ++++++++++++--- test/app/app/client.js | 6 ++++-- test/common/test.js | 9 ++++++--- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/runtime/index.ts b/src/runtime/index.ts index 43e9ee4..d0fe37d 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -59,9 +59,6 @@ function render(Component: ComponentConstructor, data: any, scroll: ScrollPositi detach(start); detach(end); } - - // preload additional routes - routes.reduce((promise: Promise, route) => promise.then(route.load), Promise.resolve()); } component = new Component({ @@ -268,3 +265,15 @@ export function goto(href: string, opts = { replaceState: false }) { window.location.href = href; } } + +export function preloadRoutes(pathnames: string[]) { + if (!routes) throw new Error(`You must call init() first`); + + return routes + .filter(route => { + return !pathnames || pathnames.some(pathname => route.pattern.test(pathname)); + }) + .reduce((promise: Promise, route) => { + return promise.then(route.load); + }, Promise.resolve()); +} \ No newline at end of file diff --git a/test/app/app/client.js b/test/app/app/client.js index 7ed4694..d69dd99 100644 --- a/test/app/app/client.js +++ b/test/app/app/client.js @@ -1,6 +1,8 @@ -import { init } from '../../../runtime.js'; +import { init, preloadRoutes } from '../../../runtime.js'; import { routes } from './manifest/client.js'; window.init = () => { return init(document.querySelector('#sapper'), routes); -}; \ No newline at end of file +}; + +window.preloadRoutes = preloadRoutes; \ No newline at end of file diff --git a/test/common/test.js b/test/common/test.js index 9e25b3c..6f47ab4 100644 --- a/test/common/test.js +++ b/test/common/test.js @@ -23,6 +23,10 @@ Nightmare.action('init', function(done) { this.evaluate_now(() => window.init(), done); }); +Nightmare.action('preloadRoutes', function(done) { + this.evaluate_now(() => window.preloadRoutes(), done); +}); + function run(env) { describe(`env=${env}`, function () { this.timeout(30000); @@ -155,7 +159,7 @@ function run(env) { }); it('navigates to a new page without reloading', () => { - return capture(() => nightmare.goto(base).init().wait(400)) + return capture(() => nightmare.goto(base).init().preloadRoutes()) .then(() => { return capture(() => nightmare.click('a[href="/about"]')); }) @@ -189,7 +193,6 @@ function run(env) { return nightmare .goto(`${base}/about`) .init() - .wait(200) .then(() => { return capture(() => { return nightmare @@ -215,7 +218,7 @@ function run(env) { it('reuses prefetch promise', () => { return nightmare .goto(`${base}/blog`) - .init().wait(300) + .init() .then(() => { return capture(() => { return nightmare