Repository navigation
Description
As mentioned in #716 and discussed at the 2018 Tokyo f2f, lazy definitions would be a useful addition to the specs.
What
A lazy definition would take a tag name and an async function that returns the class to be defined lazily. When the tag is first encountered the browser will invoke the function:
customElements.lazyDefine('my-element', async () => (await import('./my-element.js')).MyElement);For ergonomics, we may want to support a default export as the element class:
customElements.lazyDefine('my-element', () => import('./my-element.js')));Why
Dynamic imports are an important way to load code at the point in time when it's actually needed, and not cause unneeded cost and latency by loading earlier than that. Modern build tools and bundlers are able to bundle and preserve the dynamic import boundaries as code-split points. Right now this works great for situations where application code can explicitly know that it needs the new code, so we typically see it used when there's a user action or around navigation with route-based loading and therefore route-based code-splitting.
Maybe we'd see code like this to navigate:
if (page === 'product') {
const ProductPage = await import('./product-page.js');
shell.appendChild(new ProductPage());
}This is fine as long as the product-page bundle isn't itself too large, and/or most of the components in the bundle are used on every product page. But in some cases a page/route may be far too coarse grained to get effective splitting. ie, any one product page may use only a fraction of the potential features of a product page.
The recent trend is to take advantage of tooling support for dynamic import() to do component-base code-splitting.
React recently added a lazy() component wrapper:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}When OtherComponent is used, its implementation will be fetched.
In the Web Components ecosystem, Stencil builds lazy-loaded components by default. They generate a stub that is registered and loads the implementation on first creation.
On the Polymer team we have experimented with this as well with something called "SplitElement": https://github.com/PolymerLabs/split-element
These approaches work by registering a stub class with lifecycle callbacks and observedAttributed known at definition time.
The problem with the stub approach is that each element must be written to be lazy loaded, you can't just lazy load an arbitrary component. Then the implementation is non trivial as the stub has to perform something akin to upgrading between itself and the implementation class. If you want to support constructors in the implementation class, you also have to do the "constructor call trick".
It would be much nicer and more general if the platform supported this directly.
Details
defineLazy:
CustomElementRegistry#defineLazy(tagName: string, loader: () => Promise<CustomElementDefinition>)
Loading
When a lazy-defined element is created, it's associated loader function is called.
element-definition-loading Event
The elements created before the definition is loaded also fire an event: element-definition-loading. This allows generic code above the lazy elements in the tree to display user affordances while code is loading, like a spinner.
The event should carry a Promise that resolves when the element is upgraded. This Promise can be the same Promise returned by whenDefined(tagName).
Alternate Solutions
Another approach is to allow for a generic callback for potentially custom, but undefined, elements. This callback could then load and register the element definition. It's more general, but probably less ergonomic.
Polyfilling
This feature can be polyfilled by using a MutationObserver to watch for lazy element instances. In order to work in ShadowRoots, the polyfill will have to patch attachShadow.
Activity
andyearnshaw commentedon Jan 16, 2019
See #444, which this is pretty much a duplicate of.
caridy commentedon Jan 17, 2019
I don't think this is useful for very large apps with 1000+ components, and for small and midsize apps, I don't think this is really needed. The fact that we have all kind of bundlers these days, and they continue improving their capabilities seems to go against this proposal. You can just have a logic to load the pieces that you need based on the user interaction (at the app level) rather than the production of the DOM as the trigger to load the new components. Seems backward.
matthewp commentedon Jan 17, 2019
@caridy The ability to separate usage of a component from loading of a component is one of the key benefits of HTML and custom elements. I can just write
<my-widget>in my template and not have to worry about how/when it is loading.I like this proposal as it provide a hook into usage. As the OP explains, creating a stub can lead to a lot of code.
caridy commentedon Jan 18, 2019
don't get me wrong @matthewp, I'm sure that if this feature exists many folks will use it, but the question is whether or not such high level API should be provided by the UA? IMO, it should not, instead, I think low level primitives, like what is being discussed in whatwg/dom#533 is far more important because it allows app code, frameworks, and libraries to implement
customElements.lazyDefineis few lines of code, and it serves a lot other use-cases as well.justinfagnani commentedon Jan 18, 2019
@caridy That we have a lot of bundlers with improving capabilities and that interoperably do code-splitting based on dynamic import is one of the motivators for this proposal. That doesn't detract from this at all.
Please take a look at React.lazy() and Stencil.js for different approaches here. Stencil implements lazy loading, but only for Stencil components. React.lazy() just works for any React components. That's the ease-of-use I'd like to add here.
caridy commentedon Jan 18, 2019
@justinfagnani do you agree that having a low level API that allows us to do that is good enough? consider that it opens the door for others to rely on such API to do their own thing that doesn't necessarily requires the usage of a custom element, not everyone uses a custom element for everything in the page.
andyearnshaw commentedon Jan 21, 2019
I u-turned on this when I suggested it a few years ago, mainly because I realised that you can't really be sure that an element definition is loaded when you want to do anything with it programmatically. When I suggested it, we had an approach where we would define a base class,
DeferredCustomElement, that would load the relevant JS file automatically when constructed. This worked really well in very basic use cases where the element would be used declaratively in the HTML, but whenever the consumer wanted to change props or call methods using the API, we ran into issues where the element definition may not be loaded in time. We tried to counter this by including a base copy of the methods and property links, then replaying API interactions as soon as the element was upgraded, but I wasn't really happy with this.I'm an advocate of designing custom elements with the principle of least astonishment in mind, meaning that I try to make them behave how I think a native element provided by the browser would behave, mainly by linking attributes to properties, but also in other ways. Consider the following:
I expect the
console.log()to log out"bar"with my definitions because that's how my elements would behave, because that's how a native element would be expected to behave. With lazy loading you can never guarantee that the element is defined in time for the application to interact with it. We introduced a defined event for theDeferredCustomElementclass so that people could detect once the definition was fully upgraded, but in reality, telling people to use that was no different to telling them to import the definition before trying to interface with it.That being said, I do think that
MutationObserverisn't quite enough to solve this problem for custom elements that need no JavaScript interaction, as it doesn't observe across shadow trees, it doesn't account for elements created usingdocument.createElementorinnerHTML, which could also potentially start preloading the definition before those elements are added to the DOM.trusktr commentedon Jan 23, 2019
What about a way to unload element definitions? Seems like we should do something like this symmetrically: use memory when needed, but also free memory when no longer needed.
Jamesernator commentedon Apr 2, 2019
It might be useful for granularity on what triggers these registers too, for example you might have a template that uses a component in a way that it's content has been pre-rendered anyway in which case you don't really need to load the javascript until an attribute that would cause an update changes (of course you can always load it sooner if needed).
As such it might be worth just accepting any options from mutation observer init to the function:
uasan commentedon Apr 2, 2019
In practice, it is convenient to adhere to the agreement on the naming of custom tags and their accessibility at url address.
Then this is one rule for many custom tags, which can be expressed in one loader JS modules
uasan commentedon Apr 2, 2019
The trigger for
customElements.defineLazyis not to connected an element into the DOM, but to create an instance of unregistry custom element,After resolved
customElements.whenDefinedrequire auto callcustomElements.upgradefor instance by instancemyComponentjustinfagnani commentedon Apr 3, 2019
@Jamesernator I think finer-grained loading should be left to the element implementation itself.
One goal of this proposal is that in combination with a Scoped CustomElementRegistry, the use-site of an element can lazily define it in a generic way without knowing anything about its implementation (like what attributes it cares about).
If an element itself wants to lazy-load parts of its implementation based on lifecycle, attribute or children changes, or events, then it can do that internally.
Jamesernator commentedon Apr 18, 2019
@justinfagnani I don't entirely agree, assuming declarative (and hence pre-rendered) shadow DOM happens it would be useful for a pre-renderer to have an API it can target that can forgo even downloading the component unless it actually changes in a meaningful way to the component that the component would want to respond to.
Obviously a pre-renderer could just dump it's own
MutationObserverinto the page but this would be problematic as in order to observe nested shadow trees it'll need to patch.attachShadowto observe changes to elements within shadow trees and I don't think a pre-renderer should really be needing to override builtins to be able to give good performance (not to mention it's extra downloaded bytes including the observer but that should be relatively small/negligible).Having a primitive like that as part of the platform would be great because it means you only pay download costs when you actually need to modify the element rather than unconditionally loading parts of every single component that need to repeat the same logic in potentially many different files.
annevk commentedon Apr 25, 2019
One observation made during the F2F is that Firefox has an internal API that matches the alternative, a callback when a new element name is seen. Another observation was that this should likely coexist with scoped registries.
robwormald commentedon Jun 25, 2019
Currently implementing something very similar to
React.lazywith Angular's Custom Element API, and I definitely see the value in something along these lines.A simple primitive that might make this a whole lot easier would be adding the ability to lazily define
observedAttributes- most everything else can be done in userspace, but they have to be registered up front:24 remaining items
uasan commentedon Apr 26, 2023
Autoloaders in PHP are built on such event (emit on access to undefined classes), it's a really simple, understandable and powerful pattern
bicknellr commentedon Apr 26, 2023
I'm not sure this API should force its users into delaying their definitions until the next microtask checkpoint or changing the construction / upgrade order of trees depending on whether or not they contain undefined custom elements, if those behaviors aren't required. If
lazyDefine's callback's return value1 was allowed to be either a custom element class orundefined, then it would leave the user the choice of if and how to handle definition order and timing.This could be useful if you have multiple large trees that you expect to insert into the page as a result of different user actions and you want to preload definitions used in those trees after the initial page is idle but defining them all immediately after the preload completes would be too expensive. If this API doesn't allow you to provide a definition synchronously, then your large trees that have definitions that could have been supplied immediately will all have to contend with being forced to upgrade in definition order. If the API does allow you to provide a definition synchronously, then you can structure things such that your tree is still upgraded in tree order, if that's important to you.
Tree order might be important if your heavy tree contains components that expect to signal each other using events once they're connected. In the example below, maybe
<collapsible-directory>intends to display summary information about its descendants inside its own row (e.g. total size or number of items). If the definitions can't be provided synchronously then you're have to give them one at a time tocustomElements.define, so either all<collapsible-directory>s have to upgrade before all<file-row>s or vice versa.Also, I know that upgrade candidate lists were removed from the initial version of the custom elements spec, but IIRC that was mostly because the lifetime of those candidate lists was unbounded. With an API like this, where you could supply a definition synchronously, you could use candidate lists to avoid full-document tree walks because they would only need to exist for the time it takes the callback to return. The callback is called only because no element with the given tag name has been seen in an upgradable context before, so that means that if the callback returned a definition synchronously, then the only other elements with that tag name that would need to be upgraded would be those that would have attempted to upgrade during that callback, letting you avoid the full-document walk at the end. (The browser might have to sort them though.) If the callback returns
undefinedinstead, then just drop the candidate list and let thedefinecall's full-document walk do its normal thing whenever that happens.Footnotes
Or, some sync mechanism during an event listener if this was an event. ↩
justinfagnani commentedon Apr 26, 2023
Re, Events: CustomElementRegistry is not currently an EventTarget, though it could be. But I think events are less ergonomic because you can't specify what tag names you care about, so you have to filter in the event handlers.
I would still argue to keep the API consistent with the existing APIs.
whenDefined()could have been an event that fires when any definition is made, but it's much easier to use in common cases when you can specify the tag name and await the result.EisenbergEffect commentedon Apr 26, 2023
I would be interested in seeing if we can make the registry an EventTarget. Let it dispatch events in both scenarios: when an unknown element is encountered and when an element is defined. The promise-based APIs could easily be defined as sugar over the event with a filter on tag name. Also, very easy to provide library-specific convenience over top of these APIs. The main thing about this approach is that it seems to enable all the use cases.
claviska commentedon Apr 26, 2023
I could get behind an event if we had a cheap way to query the registry for unregistered elements already on the page. Without that, an event would require a discovery method and DOM traversal to find elements added before the listener.
I like the ergonomics of @justinfagnani’s initial post. Pre-registering and offloading the import mechanism to the user would satisfy all the use cases I currently have for this feature.
Related: I recently built an auto loader for Shoelace using a mutation observer. It has a similar problem in that it requires an initial discovery method that runs since I can’t guarantee the auto loader initializes before custom elements are in the DOM. It uses
querySelectorAll()and the:not(:defined)selector, but it’s still a query I’d like to avoid.A promise-based syntax makes auto loading trivial, as long as the tag names are known ahead of time. That said, there still could be a gap for unknown elements that events would solve. But again, we’d need a low cost way to query for unregistered elements in a document for this to be a complete solution.
keithamus commentedon Apr 27, 2023
Why would
CustomElementRegistryneed to be an event target?HTMLUnknownElementscould emit events when they're connected, which could bubble. This way one could listen for, say, anunknown-elementevent on the document, and be able to get thetargetto reason about what to do about it. This would be complementary to CE APIs.WRT to extending the Custom Element APIs, would overloading
define()to take aPromise<CustomElementConstructor> | CustomElementConstructorbe an option?EisenbergEffect commentedon Apr 27, 2023
@keithamus That works for me. Also solves the issue of deeply nested elements and custom registries.
keithamus commentedon Apr 27, 2023
For me one of the larger motivations for something like
lazyDefineis less about the complexity (it's fairly straightforward to implement with a few LOC) and more about having a centralised place, avoiding multiple calls to define an element which raise exceptions after some number of async cycles. Having a mechanism likelazyDefine(ordefine(name, Promise)) would be useful to avoid kicking off work to define a component multiple times.justinfagnani commentedon Apr 27, 2023
@keithamus
That sounds a lot like mutation events, which afaik are untenable.
@EisenbergEffect
What problem are you referring to here?
EisenbergEffect commentedon Apr 27, 2023
I think we need to back up and start with some scenarios from the real world. We're each jumping to APIs without adequately explaining the scenarios that are driving the need for a new capability. What I'm trying to say is that the scenarios I have aren't solved by the simple lazy load API proposed here. However, they are solved by the alternate proposal of a more generic callback for unknown elements.
I am happy to contribute some scenarios from the real world. @justinfagnani Do you want me to drop them here or do you want to collect them in an alternate location?
justinfagnani commentedon Apr 27, 2023
Yeah, can you list the scenarios?
I don't see how deeply nested elements would effect any API shape we've discussed though. Custom element registries are already invoked for any potentially custom element. This is how non-lazy definitions work. So in any case where an element would have potentially upgraded the registry could see a lazy definition and invoke whatever callback/event/Promise the API uses.
EisenbergEffect commentedon Apr 27, 2023
There may not be a problem with custom registries. But it feels to me like the broader set of scenarios that need the more general hook for unknown elements is not being understood well. I'll add some scenarios here when I get a block of time to write it up. Maybe tomorrow or early next week depending on how things go.
EisenbergEffect commentedon May 9, 2023
Here's a scenario from a real-world, well-known site that is heavily invested in Web Components, where the architecture could really benefit from some sort of lazy loading platform feature as is being discussed here...
Let's say you are building a feeds experience. Each feed is customized to a specific user. The feeds themselves are an infinite scrolling list of cards. Each card is a Web Component. The experiences that these card components afford are highly diverse and there are hundreds of different cards with the number growing all the time. There is a central engineering team that creates the shell and many of the cards, but a large portion of them are created by other engineering teams and partners, which have a business case for plugging into the overall feeds experience.
When any given user visits the site, the frontend queries a service to find the specific set of content for that user at that point in time. This content can contain any combination of the hundreds of cards available from the library, but the specific combination cannot be determined ahead of time, as it is based on preferences, current events, time of day, external advertising services, etc. As the user scrolls, additional data is loaded which the client then dynamically renders. At any point of in time, the core engineering team or partners may launch new card experiences and the backend services may begin sending back data for cards that did not exist at the time that the original server request was made by the client.
I won't get into the details of how this is/should be handled today with the current standards, but it's very non-trivial and less than ideal. However, it seems that one way the existing system could be simplified and improved is if the frontend could simply detect an HTML element that showed up which was undefined. It could then send a request to the server to get the batch of definitions (all unknowns seen within a current tick). Please note that upfront defining all lazily-loadable element names is not feasible in this context. Again, there are hundreds of experiences, which could amount to thousands of elements, and those can change while the user is interacting with the site at any point in time.
The use cases are even more interesting though. As the client may not want to simply load any element it doesn't have a definition for. Certain elements it may want to delay load until certain things happen. A typical example is the settings UI for the feeds experience. Most of the time that a customer visits the site, they don't mess with their settings. So, it's wasteful to load it. Instead, you want to load that set of components when some app-specific heuristics determine that the user is about to interact with the settings. Similar rules may also be applied to various cards within the library, which have more or less complex interactions. For example, a quiz/survey card may not want to load all its behavior unless a user signals that they are about to engage with the quiz/survey. A card that contains a casual game may not want to load until the user signals they want to play. The rules for what to load and when are application and experience-specific and are constantly being changed based on analysis of RUM data. In fact, these rules themselves may be user-specific.
frederikbosch commentedon Mar 14, 2025
I am running into a very similar scenario. I have many pages without large components or even without components at all. An
unknown-elementevent as suggested @keithamus would allow to load the elements only when present in the DOM. With an additional CSS state:definingit would be possible to show a spinner or other loading state graphic while the promise is being resolved.Another option would be to access a list of unknown elements after parsing the DOM. Something like:
frederikbosch commentedon Apr 11, 2025
Another approach - I believe I have not seen it - is to solve this via the
importside. Why not extend theimportmapspecification with acustom-elementskey?{ "custom-elements": { "my-element": "import/default/from/file.js", "another-element": { "import": { "file": "import/from/file.js" "name": "register" } } } }