[WICG/webcomponents] Anonymous Custom Elements (Issue #1074)

I would like to discuss the possibility of using custom elements without requiring the custom element registry.

## Overview 

Allowing a custom element to be used without a custom element registry allows us to sidestep a lot of the issues around the global registry that are discussed in #716. Instead of introducing a new registry we allow a per-element definition. 

In order to get the conversation started I propose the working name of anonymous custom elements. The primary drive is to couple custom elements with ESM modules. This would require no changes to the DOM-api as we can simply use a constructor directly.

```js
// my-example.js
export class MyExampleElement extends HTMLElement {
  constructor() {
    super()
    const root = this.attachShadow({ mode: 'open' })
    root.innerHTML = '<span>example</span>'
  }
}

// index.js
import { MyExampleElement } from './my-example.js' 
document.body.appendChild(new MyExampleElement ())
```

The HTML for this could be 

```html
<body>
  <anonymous>
    #shadow
      <span>example</span>
  </anonymous>
</body>
```

This new `<anonymous>` element would keep track of the module that defines the custom element in the property `module` and the constructor in a property `definition`. In the example above `module` would be the value of `import.meta.url` and `definition` the local name of `MyExampleElement` in that module. 

These two would also allow for an HTML API. 

```html
<anonymous module="./my-example.js" definition="MyExampleElement"></anonymous>
```

This would load the ESM module `./my-example.js` and use the constructor defined from that module. A similar thing could be done via DOM

```
const anonymous = document.createElement('anonymous') 
anonymous.module  = './my-example.js'
anonymous.definition = 'MyExampleElement'
document.body.appendChild(anonymous)
```

## Benefits

- Utilizing ESM-modules instead of a registry allow for custom elements to be defined more closely to what one would expect coming from other component systems. 
- Since tag name is not relevant a lot of the edge cases that arise with scoped element registries are sidestep entirely.
- Additionally this adds a much needed feature of on demand loading of custom elements based on usage.

## Drawbacks

- Possibly SSR support for a feature like this could be hard. Should declarative shadow DOM be allowed? 
- Not possible to target specific custom elements with tag selectors.

 I am happy to explore this idea with you all. This is my first issue so please guide me if something is missing or is formatted incorrectly. 

-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/1074
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/1074@github.com>

Received on Monday, 30 September 2024 17:17:43 UTC