Show loading before load and hide after load

#47 · closed · 4 comments

View on GitHub ↗

paulocoutinhox

Hi, How i can receive a generic event before load component and after load it? My components .js file are loaded dynamically, so it still on home until the .js file is loaded. So i want show a loading toast and hide after it was loaded. ``` const router = Navaid("/") .on("/", () => run(import("../routes/Home.svelte"))) .on("/about", () => run(import("../routes/About.svelte"))) ``` Can you help me? Thanks.

Comments

lukeed

Hey, so because you have your own `run` function there, you'd have it contain the loader display logic within it. If you send a repro I can help you over the finish line, but tough to provide a generic solution without seeing `run` directly.

paulocoutinhox

Hi, This is what i do. ``` function onReplaceState(obj) { uri = obj.state || obj.uri || location.pathname; afterLoadRoute(); } function onPushState(obj) { uri = obj.state || obj.uri || location.pathname; afterLoadRoute(); } function onPopState(obj) { uri = obj.state || obj.uri || location.pathname; } function beforeLoadRoute() { pageLoadingBar.update(() => true); } function afterLoadRoute() { pageLoadingBar.update(() => false); } addEventListener("replacestate", onReplaceState); addEventListener("pushstate", onPushState); addEventListener("popstate", onPopState); const router = Navaid("/") .on("/", () => { beforeLoadRoute(); run(import("../routes/Home.svelte")); afterLoadRoute(); }) .on("/about", () => { beforeLoadRoute(); run(import("../routes/About.svelte")); afterLoadRoute(); }) ```

paulocoutinhox

But it doesnt work. Because it dont show the bar while load the component. Example: https://util123.com

lukeed

Sorry, I was asking to see the `run` function itself. But yes, this doesn't work because `run()` finishes execution immediately (it's dealing with asynchronous stuff internally) and so your `beforeLoadRoute` and `afterLoadRoute` all execute at basically the same time. I'm going to assume your `run` function looks something like [this](https://github.com/lukeed/svelte-demo/blob/master/src/components/App.svelte#L10-L29), so the example below is going to build upon that: ```js function run(thunk, obj) { const target = uri; thunk.then(m => { if (target !== uri) return; // HAVE UNIQUE ROUTE TO FETCH // inline: beforeLoadRoute pageLoadingBar.update(() => true); params = obj || {}; if (m.preload) { m.preload({ params }).then(() => { if (target !== uri) return; Route = m.default; window.scrollTo(0, 0); // DONE LOADING // inline: afterLoadRoute pageLoadingBar.update(() => false); }); } else { Route = m.default; window.scrollTo(0, 0); // DONE LOADING // inline: afterLoadRoute pageLoadingBar.update(() => false); } }); } ``` Hope that helps! Closing, but please follow up if you still have a question