home ~ socials ~ projects ~ rss

Using JavaScript Classes from the Parent Page of a Web Component

September 2025

I'm building a web component that needs to load functionality dynamically from its parent page.

I'm doing it by creating a global variable named "customClasses" in a regular <script> tag in the <head> element on the page1. Class definitions with the necessary functionality are placed inside it.

HTML

<script>
const customClasses = {};
customClasses.Widget = class {
  update(el) {
    el.innerHTML = "Connected";
  }
}
</script>

Output

I'm using a data-* attribute to send in the name of the class I want to use from the instance of the component.

HTML

<test-component data-connect="Widget">
  waiting...
</test-component>

The web component grabs the name from the dataset and uses it to create an internal instance of the desired class via the "customClasses" object. It can then use it as necessary.

JavaScript
class TestComponent extends HTMLElement {
  connectedCallback() {
    if (
      typeof this.dataset.connect !== "undefined"
      && typeof customClasses !== "undefined"
      && typeof customClasses[this.dataset.connect] !== "undefined")
    {
      this.widget = new customClasses[this.dataset.connect]();
      this.widget.update(this);
    } else {
      console.error("Could not make connection.");
    }
  }
}

customElements.define("test-component", TestComponent);

Everything is working as far as I can tell.

HTML

<test-component data-connect="Widget">
  waiting...
</test-component>

Output

Connected

But, this feels like one of those things where there might be hidden gotchas or show-stoppers I haven't learned about yet. Please give me a heads up if there's something I should know about.

-a

end of line

Endnotes

The example is simplified as much as I know how. Part of the simplification involved having the component update its own text by jumping through the instance of the external class.

That specific update would be easier to do directly inside the component. But, it's not the point of the example. It's merely acting as a stand in for more complicated functionality that would only make the example harder to follow.

Footnotes

Specifically, it's a <script> tag and not a <script type="module"> tag.

Share link:
https://www.alanwsmith.com/en/32/m1/a4/mm/?using-javascript-classes-from-the-parent-page-of-a-web-component