Re: [w3c/webcomponents] Lazy Custom Element Definitions (#782)

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:

```html
<my-element id="myEl" foo="bar"></my-element>
<!-- load the script that sets up element definitions -->
<script src="custom-elements.js"></script>
<script>
  console.log(myEl.foo);
</script>
```

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 the `DeferredCustomElement` class 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 `MutationObserver` isn'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 using `document.createElement` or `innerHTML`, which could also potentially start preloading the definition before those elements are added to the DOM.


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/782#issuecomment-456015532

Received on Monday, 21 January 2019 10:02:35 UTC