- Notifications
You must be signed in to change notification settings - Fork12
Dynamically load a svelte component
License
kaisermann/svelte-loadable
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Dynamically load a svelte component. Based onreact-loadable.
Just pass aloader method which return a async module import:
<script>importLoadablefrom'svelte-loadable'</script><Loadableloader={() => import('./AsyncComponent.svelte')} />
Useunloader to preventLoadable from caching the component which will cause it to callloader each time the component is used after being unmounted.
<script>importLoadablefrom'svelte-loadable'// unloader callbackfunctionunloader(){// some code here}</script><!-- unloader as boolean --><Loadable...unloader/><Loadable...unloader="{true}"/><Loadable...unloader="{someBooleanValue}"/><!-- unloader as predefined function in script tag above --><Loadable...{unloader}/><!-- unloader as an inline function --><Loadable...unloader={() => { /* some code here */ }} /><!-- example using SystemJS Module Loader which has the ability to unload (delete) a previously loaded module --><Loadableloader={() => System.import('./AsyncComponent.svelte')} unloader={()=> System.delete(System.resolve('./AsyncComponent.svelte'))}/>
loader: a function whichimport()your component to the<Loadable>component.delay: minimum delay inmsecsfor showing theloading slot. Default: 200timeout: time inmsecsfor showing thetimeout slot.unloader:trueto prevent the component from being cached or afunctionwhich will also prevent the component from being cached after being unmounted and will be called immediately after it is removed from cache.
Any other prop will be passed directly onto the rendered component if thedefault slot is defined:
<Loadableloader="{...}"foo="cookie"bar="potato"/><!-- `foo` and `bar` will be available to the rendered component -->
If the default slot is used, it's up to the developer to render the component:
<Loadableloader="{...}"let:component><svelte:componentthis="{component}"foo="cookie"bar="potato"/></Loadable>
on:load: a function which is executed right after the<Loadable>component is loaded.
<Loadableon:load={() => console.log('The component has been loaded')}loader={...} />
Otherwise, if your callback contains more code, you can wrap it into a function, and call it without parentheses
<Loadableon:load="{callback}"loader="{...}"/>
loading: customizes the loading state;error: customizes the error state. You canlet:errorto have access to the error variable, andlet:retryto have access to the retry method.timeout: customizes the timeout state. Will only appear iftimeoutprop is defined;default: customizes the imported component render (add props, etc). You canlet:componentto access the imported component constructor.
<script>importLoadablefrom'svelte-loadable'</script><Loadableloader={() => import('./AsyncComponent.svelte')}><divslot="loading">Loading...</div><divslot="error"let:errorlet:retry> {error}<br><buttonon:click={retry}>Try again</button></div></Loadable>
By default, Svelte Loadable will dynamically load the specified loader (import statement) every time the component is initialized and reinitialized. This creates a delay between initial rendering, and rending the loaded component, even for components which have previously been loaded. To work around that, Svelte Loadable provides an optional cache, which can be used to predefine a loader, and keep track of whether it has already been loaded. When a loader is registered, it will render immediately on the next initialization.
To set that up, you'll need toregister the loader at definition time in a module script block, instead of passing the loader directly to the loadable component instance, then pass the resulting loader on to the loadable component. It looks like this (withsvelte-routing).
NOTE: A resolve function is necessary for most SSR solutions. The function must return an absolute path, which will be used for indexing, and for loading before hydration. The specific way to generate that may vary by platform. A babel plugin for Svelte Loadable to help generate that automatically is forthcoming.
App.svelte:
<scriptcontext="module">import{register}from'svelte-loadable'// Loaders must be registered outside of the render tree.constPageLoader=register({loader:()=>import('./pages/Page.svelte'),resolve:()=>require.resolve('./pages/Page.svelte'),})constHomeLoader=register({loader:()=>import('./home/Home.svelte'),resolve:()=>require.resolve('./home/Home.svelte'),})</script><script>import{Router,Link,Route}from'svelte-routing'importLoadablefrom'svelte-loadable'exportleturl=''</script><Routerurl="{url}"><Routepath="/pages/:slug"let:params><Loadableloader="{PageLoader}"slug="{params.slug}"><divslot="loading">Loading...</div></Loadable></Route><Routepath="/"><Loadableloader="{HomeLoader}"/></Route></Router>
Another advantage is that if the same module is registered in two different places in the tree, the previous loader will be used instead of creating a second loader.
This comes with additional benefits and opportunities as well. There is now apreloadAll method, which can be used to proactively (and recursively) preload all the modules after the initial render of the application, if desired. That method can also be used server side to preload all the necessary components to pull off server side rendering (SSR).
Preloads all registered Loaders. Works server side, and client side.
import{preloadAll}from'svelte-loadable'// Somewhere in your code, after the initial tree is rendered:preloadAll().then(()=>{...});
To facilitate the creation of SSR solutions, Svelte Loadable uses a context which can be set up by an SSR solution in aLoadableProvider using the string identifier 'svelte-loadable-capture'. Svelte Loadable expects the context to provide a method, to which it will pass the registered loader function. For an example implementation, check outnpdev:svelte-loadable a Meteor SSR solution.
For more examples, please check theexample/src/App.svelte file.
About
Dynamically load a svelte component
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.