• Stars
    star
    319
  • Rank 130,706 (Top 3 %)
  • Language Svelte
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Dynamically load a svelte component

svelte-loadable

Dynamically load a svelte component. Based on react-loadable.

Usage

Just pass a loader method which return a async module import:

<script>
  import Loadable from 'svelte-loadable'
</script>

<Loadable loader={() => import('./AsyncComponent.svelte')} />

Use unloader to prevent Loadable from caching the component which will cause it to call loader each time the component is used after being unmounted.

<script>
  import Loadable from 'svelte-loadable'

  // unloader callback
  function unloader() {
    // 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 -->
<Loadable loader={() => System.import('./AsyncComponent.svelte')} unloader={()
=> System.delete(System.resolve('./AsyncComponent.svelte'))} />

Props

  • loader: a function which import() your component to the <Loadable> component.
  • delay: minimum delay in msecs for showing the loading slot. Default: 200
  • timeout: time in msecs for showing the timeout slot.
  • unloader: true to prevent the component from being cached or a function which 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 the default slot is defined:

<Loadable loader="{...}" 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:

<Loadable loader="{...}" let:component>
  <svelte:component this="{component}" foo="cookie" bar="potato" />
</Loadable>

Events

  • on:load: a function which is executed right after the <Loadable> component is loaded.
<Loadable on: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

<Loadable on:load="{callback}" loader="{...}" />

Slots

  • loading: customizes the loading state;
  • error: customizes the error state. You can let:error to have access to the error variable, and let:retry to have access to the retry method.
  • timeout: customizes the timeout state. Will only appear if timeout prop is defined;
  • default: customizes the imported component render (add props, etc). You can let:component to access the imported component constructor.

Basic Example

<script>
  import Loadable from 'svelte-loadable'
</script>

<Loadable loader={() => import('./AsyncComponent.svelte')}>
  <div slot="loading">Loading...</div>
  <div slot="error" let:error let:retry>
    {error}
    <br>
    <button on:click={retry}>Try again</button>
  </div>
</Loadable>

Registering a loader

Or, preventing "flash of loading"

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 to register 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 (with svelte-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:

<script context="module">
  import { register } from 'svelte-loadable'

  // Loaders must be registered outside of the render tree.
  const PageLoader = register({
    loader: () => import('./pages/Page.svelte'),
    resolve: () => require.resolve('./pages/Page.svelte'),
  })
  const HomeLoader = register({
    loader: () => import('./home/Home.svelte'),
    resolve: () => require.resolve('./home/Home.svelte'),
  })
</script>

<script>
  import { Router, Link, Route } from 'svelte-routing'
  import Loadable from 'svelte-loadable'

  export let url = ''
</script>

<Router url="{url}">
  <Route path="/pages/:slug" let:params>
    <Loadable loader="{PageLoader}" slug="{params.slug}">
      <div slot="loading">Loading...</div>
    </Loadable>
  </Route>
  <Route path="/">
    <Loadable loader="{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 a preloadAll 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).

Additional Methods

preloadAll()

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(() => {...});

The 'svelte-loadable-capture' Context for SSR

To facilitate the creation of SSR solutions, Svelte Loadable uses a context which can be set up by an SSR solution in a LoadableProvider 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 out npdev:svelte-loadable a Meteor SSR solution.


For more examples, please check the example/src/App.svelte file.

More Repositories

1

svelte-i18n

Internationalization library for Svelte
TypeScript
1,216
star
2

svelte-css-vars

✨ Ever wanted to have reactive css variables in svelte? What if I told you there's a way?
JavaScript
235
star
3

kaisermann

πŸ“Ί Personal website and Github profile readme ✨
JavaScript
96
star
4

selene

A opinionated Wordpress base theme based on Sage.
PHP
29
star
5

sapper-template-i18n

Sapper template with an opinionated svelte-i18n usage
JavaScript
25
star
6

pr-slack-bot

A bot that keeps track of your PRs posted on slack
JavaScript
19
star
7

comicbubbles

CSS-only 8 bit-like comic balloons
CSS
18
star
8

svelte-page

Router component for Svelte
HTML
18
star
9

aph

Minimal DOM, barely api-less, manipulation library
JavaScript
16
star
10

PhotoSwippy

A no-(extra)-dependency PhotoSwipe friendly wrapper
JavaScript
12
star
11

rolleiflex

A Flexbox grid & helper framework made with Stylus and BEVM
CSS
9
star
12

svelte-markup-walker

A Svelte preprocessor that allows to walk through the AST generated by the svelte parser and modify the markup with MagicString.
TypeScript
9
star
13

textlooper

Customizable and lightweight text content looper based on CSS animations.
JavaScript
9
star
14

kiwi

πŸ₯πŸ›  Kiwi Tooling is a very dear and hand-crafted front-end tooling preset that aims to guide you on writing readable code for humans.
JavaScript
8
star
15

copymoji

click copy emoji
HTML
6
star
16

.dotfiles

Installs brew, wp-cli, composer, fish and a whole lot of things
Vim Script
6
star
17

marmitas.top

JavaScript
5
star
18

WPDLS

Basic custom WordPress admin style made easy
CSS
4
star
19

crius

A flexible and modular gulp front-end workflow
JavaScript
4
star
20

js-boilerplate

Barebones JS project boilerplate
JavaScript
3
star
21

post-links

Open links using POST instead of GET
JavaScript
3
star
22

vitorify

Copy and paste the bullshit, spend your energy elsewhere.
JavaScript
3
star
23

v1.kaisermann.me

Astro
2
star
24

10de10-generator

CSS
2
star
25

arke

A static/WordPress website setup-deploy tool
Python
2
star
26

expression-calculator

Simple exercise of a math expression calculator
JavaScript
2
star
27

ragnarok-scripts

A small collection of the old scripts I made for the Cronus-Emulator
2
star
28

quickenv

JavaScript
2
star
29

text-emoji-generator

HTML
1
star
30

jeopardy

Svelte
1
star
31

visc

Elements visibility state on viewport
JavaScript
1
star
32

programadeindie.com

PHP
1
star
33

s.olar.dance

CSS
1
star
34

stone-test

JavaScript
1
star
35

ti-queue

Timed Invocation Queue
JavaScript
1
star
36

find-my-puc

Projeto final para o curso de Sistemas de Informação
PHP
1
star
37

hyperion

A static website workflow forked from Crius
JavaScript
1
star
38

codigo-conduta-10de10

1
star
39

signature.kaisermann.me

My personal centralized website signature helper scripts.
JavaScript
1
star
40

lab

Created with CodeSandbox
JavaScript
1
star