DEV Community

David Rickard
David Rickard

Posted on

3 2

Lazy loading Web Components with WebPack in 1 minute

Normally when you define a web component with Lit or FAST you might do something like this:

import { MyComponent } from "./MyComponent";

MyComponent; // Stop tree-shaking
Enter fullscreen mode Exit fullscreen mode

As part of importing the module, it defines the <my-component> element that you want to put in DOM.

That works just fine but now that web component's Javascript is part of the same bundle as whatever was calling it. What if it's just some dialog picker that rarely gets called, or always called far after the main page load?

Just run this line when you need to show that component.

await import("./MyComponent ");
Enter fullscreen mode Exit fullscreen mode

Webpack will see that it's a dynamic import, create a new bundle for it and download it when the code is run. That will define <my-component> and automatically upgrade any of them you have in your DOM already.

I was rather shocked with how easy it was to do. Just remember that if what you are loading in needs to be tree-shaken you'll need to create an intermediate "lazy" module to help Webpack do that.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay