0.0.1-rc.9 • Published 1 year ago

@somehow-digital/web-component-loader v0.0.1-rc.9

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Web Component Loader

Utility for lazy-loading web components.

Web Component Loader uses the IntersectionObserver API to defer loading components until they enter the viewport. It also uses the MutationObserver API to observe the DOM for newly inserted components. This allows to dynamically insert components into the DOM and have them loaded automatically.

  • 📦 small: 1.5kb minified
  • 🚀 fast: Uses IntersectionObserver to defer loading components
  • 🧩 flexible: Provides a class and a function for loading components
  • 🎨 customizable: Define various options for loading components

Setup

npm install @somehow-digital/web-component-loader

Usage

Web Component Loader provides a class and a function for loading components. The utility function is a wrapper around the class. The class is more flexible, but the function is more convenient.

Class

The class is a wrapper around the customElements.define function. It allows you to define components and then run the loader. This is useful if you want to define components in one place and then run the loader in another.

import Loader from '@somehow-digital/web-component-loader';

const loader = new Loader(/* options */);
loader.register('component-one', () => import('component-one.js'));
loader.register('component-two', () => import('component-two.js'), /* options */);

Function

The function returns a function that can be called to run the loader. This is useful to run the loader independently of the component definitions.

import { register } from '@somehow-digital/web-component-loader';

register({
  'component-one': () => import('component-one.js'),
  'component-two': [() => import('component-two.js'), /* options */],
})(/* options */);

Options

Options can be passed to the register function or the Loader class. Options can be set globally or some can be set per component definition. See file loader.ts for the default values.

OptionTypeDefaultGlobalElementDescription
contextHTMLElementdocumentThe DOM context to search for components in.
initbooleantrueWhether to run the loader immediately.
contextualbooleantrueWhether to load components found in the DOM context.
deferbooleantrueWhether to defer loading components on entering the viewport.
observebooleantrueWhether to observe the DOM for newly inserted components.
definebooleantrueWhether to define components when loading them.
marginstring0pxThe margin used when loading deferred elements.
selectorfunction...Selector to use when searching for components.
excludesstring[][...]An array of element names to exclude from processing.

somehow.digital

0.0.1-rc.9

1 year ago

0.0.1-rc.8

1 year ago

0.0.1-rc.7

1 year ago

0.0.1-rc.6

1 year ago

0.0.1-rc.5

1 year ago

0.0.1-rc.4

1 year ago

0.0.1-rc.3

1 year ago

0.0.1-rc.2

1 year ago