All Projects → kaisermann → Svelte Loadable

kaisermann / Svelte Loadable

Licence: mit
Dynamically load a svelte component

Projects that are alternatives of or similar to Svelte Loadable

Modular Css
A streamlined reinterpretation of CSS Modules via CLI, API, Browserify, Rollup, Webpack, or PostCSS
Stars: ✭ 234 (+4.93%)
Mutual labels:  code-splitting, svelte
Starter Pack
Combines React (ft. hooks), Redux, Redux-saga and TypeScript with Auth0 as a starting point for modern web apps with solid authentication
Stars: ✭ 209 (-6.28%)
Mutual labels:  code-splitting
React Ssr Boilerplate
Boilerplate for React apps with routing, code splitting, & server side rendering
Stars: ✭ 183 (-17.94%)
Mutual labels:  code-splitting
Sveltesociety.dev
Community website for Svelte Society. The site will contain a component library list, a cookbook, tutorials, event information, talks etc.
Stars: ✭ 199 (-10.76%)
Mutual labels:  svelte
Modheader
ModHeader browser extension
Stars: ✭ 184 (-17.49%)
Mutual labels:  svelte
Awesome Svelte
⚡ A curated list of awesome Svelte resources
Stars: ✭ 204 (-8.52%)
Mutual labels:  svelte
React Hooks In Svelte
React hook examples ported to Svelte
Stars: ✭ 176 (-21.08%)
Mutual labels:  svelte
React Pwa
An upgradable boilerplate for Progressive web applications (PWA) with server side rendering, build with SEO in mind and achieving max page speed and optimized user experience.
Stars: ✭ 2,433 (+991.03%)
Mutual labels:  code-splitting
Svelte Component Template
A base for building shareable Svelte 3 components
Stars: ✭ 208 (-6.73%)
Mutual labels:  svelte
Bundle Buddy Webpack Plugin
🐐🐐🐐🐐 bundle-buddy-webpack-plugin 🐐🐐🐐🐐
Stars: ✭ 199 (-10.76%)
Mutual labels:  code-splitting
Markuplint
A Linter for All Markup Languages.
Stars: ✭ 193 (-13.45%)
Mutual labels:  svelte
Celestite
Beautifully reactive, server-side rendered Svelte apps w/ a Crystal backend
Stars: ✭ 185 (-17.04%)
Mutual labels:  svelte
Svelte Storybook Tailwind
A starter template for Svelte, TailwindCSS and Storybook. You can easily start your project with this template, instead of wasting time figuring out configurations for each integration.
Stars: ✭ 204 (-8.52%)
Mutual labels:  svelte
Attractions
A pretty cool UI kit for Svelte
Stars: ✭ 179 (-19.73%)
Mutual labels:  svelte
Svelte Vscode
Svelte language support for VS Code
Stars: ✭ 211 (-5.38%)
Mutual labels:  svelte
Svelte Sight
A Svelte dev tool for visualizing component hierarchy, state, and props of your application
Stars: ✭ 179 (-19.73%)
Mutual labels:  svelte
Svelte Awesome
Awesome SVG icon component for Svelte JS, built with Font Awesome icons. Based on Justineo/vue-awesome
Stars: ✭ 193 (-13.45%)
Mutual labels:  svelte
Ui
🏁🌐 Frontend Svelte PWA starter for SaaS startups
Stars: ✭ 200 (-10.31%)
Mutual labels:  svelte
Svelte Notifications
Simple and flexible notifications system
Stars: ✭ 217 (-2.69%)
Mutual labels:  svelte
Parcel Plugin Svelte
A parcel plugin that enables svelte support
Stars: ✭ 214 (-4.04%)
Mutual labels:  svelte

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;
  • 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 bind:this={loadable} loader={() => import('./AsyncComponent.svelte')}>
  <div slot="loading">Loading...</div>
  <div slot="error" let:error>
    {error}
    <br>
    <button on:click="loadable.load()">Try again</button>
  </div>
</Loadable>

Methods

  • Use the .load() method to retry loading.

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].