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

Here's one experiment I made on the idea.

---
I did implement a minimal version of lazy loading as an ESM module loaded over http.

There's probably other ways to do.

This works well when I build pages and want to load only things I use in the view. One `esm-module` file per component/feature. In my usage, I serve over those from my own domain name, that’s proxyied by something like Fastly/CloudFlare, I serve proper `content-type` (and `Access-Control-Allow-Origin`) when calls are coming from known origins I control.


## Definition

```js
/**
 * File: https://renoirb.com/esm-modules/value-boolean-element.mjs
 */


export class ValueBooleanElement extends HTMLElement {
  /* ... */
}

/**
 * EXAMPLE LazyLoader
 */
export const registerCustomElement = (
  { customElements },
  localName = 'value-boolean',
) => {
  let pickedName = localName.toLowerCase()
  if (/^[a-z]([\w\d-])+$/.test(pickedName) === false) {
    const message = `Invalid element name "${pickedName}", it must only contain letters and dash.`
    console.warn(message)
    pickedName = 'value-boolean'
  }
  if (!customElements.get(pickedName)) {
    customElements.define(pickedName, ValueBooleanElement)
  } else {
    console.log(
      `ERR\t customElements.define <${pickedName} />, already defined.`,
    )
  }
}

/**
 * URL Query param to tell via URL which name to use to register to the realm 
 * it's getting loaded into.
 *
 * ?registerElement=my-foo
 */
const registerElement = new URL(import.meta.url).searchParams.get(
  'registerElement',
)
if (registerElement) {
  try {
    window && registerCustomElement(window, registerElement)
  } catch (e) {
    console.log(`ERR\t No access to global window: ${e}`)
  }
}
```

## Usage

```html
<html>
  <body>
    <my-value-boolean></my-value-boolean>

    <!-- Eventually, somehow -->
    <script type="module">
      import from 'https://renoirb.com/esm-modules/value-boolean-element.mjs?registerElement=my-value-boolean'
    </script>
  </body>
</html>
```

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

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

Received on Monday, 24 April 2023 01:22:17 UTC