A few days ago, Remy Sharp was wondering about name collisions for custom elements and I replied with my opinion that custom element authors should allow their consumers to register the custom elements themselves and just export the class. This morning both Chris Ferdinandi and Óscar Otero made posts about the convenience of a single script which had me rethinking my earlier suggestion.

Personally, I still think that as a custom element author, I want to give my consumers the most flexibility for how to use a custom element I’ve created:

  • I want to do what I can to help them avoid name collisions.
  • I don’t want to assume their conditions for defining a custom element.
  • I want to support consumers who want to use scoped custom element registeries in the future.

However, I began to wonder how I could add the convenience offered by a single script solution.

I could just include an additional file that handles the definition:

import { BlehBlehBlehElement } from "./bleh-bleh-bleh-element.js";

customElements.define("bleh-bleh-bleh", BlehBlehBlehElement);

But this really is such an insignificant amount of code and it introduces nested imports. The latter is resolvable with a preload, but it still creates complexity and a potential footgun for consumers.

I also could create a bundle for that file… but I like to not use build tools whenever I can since I don’t want the complexity myself.

This got me thinking about import.meta. For modules, import.meta includes the URL used to load the module. This means we can create an additional API for the module using its URL’s search params.

So in our case, we can just conditionally define the element when the ?define search param is set:

// Export the class so the consumer can register the element with greater flexibility
export class BlehBlehBlehElement extends HTMLElement {
	constructor() {
		super();
		if (!this.shadowRoot) this.attachShadow({ mode: "open" });
		this.shadowRoot.innerHTML = "🧛";
	}
}

// Check if `?define` is set and if so, define it in the default registry
if (new URL(import.meta.url).searchParams.has("define")) {
	customElements.define("bleh-bleh-bleh", BlehBlehBlehElement);
}

Here’s how a consumer of the custom element would use it:

<!doctype html>
<title>Bleh bleh bleh – Drac</title>
<script type=module src=./bleh-bleh-bleh-element.js?define></script>

<bleh-bleh-bleh></bleh-bleh-bleh>

Is this a bad idea? Sure, the script must be a module now (i.e. you must set type=module on its <script> element), but that’s likely a good thing.

Anyway, I thought this was a pretty neat way to keep things simple for both a custom element author and consumer. Let me know what you think.