2

I have been trying to create some components using litelement. Is there any way to prevent importing every component and import dynamically only required components

1 Answers1

2

Lit elements are JavaScript classes and don't require any global framework state, so they can be code split and executed with whatever build system you have in place.

For example, you can import and define elements dynamically using a dynamic import (or any other lazy code fetch/execution mechanism you can use in JavaScript).

See a simple example: https://lit.dev/playground/#gist=b55407e8ebbf88a9b8cab11a259539a8

Breaking down the example. The code containing the <simple-greeting> litelement is contained in simple-greeting.js. This is loaded using a dynamic import on the press of a button with the following code:

document.querySelector('button').addEventListener('click', () => {
    // On button press load the component definition and define
    // on custom element registry.
    import('./simple-greeting.js');
});

Now the component's code won't be loaded and the element will not be defined until the programmatic dynamic import has happened.

The browser natively handles upgrading the custom elements on the page when they are defined on the custom element registry.

YouCodeThings
  • 590
  • 3
  • 13