Skip to content
Advertisement

How do I separate the HTML markup in my custom element?

I have a custom element that displays a message inside three nested divs:

class HelloWorld extends HTMLElement {
    connectedCallback() {
        const div1 = document.createElement('div')
        this.appendChild(div1)
        
        const div2 = document.createElement('div')
        div1.appendChild(div2)
        
        const div3 = document.createElement('div')
        div3.textContent = 'Hello World!';
        div2.appendChild(div3)
    }
}
customElements.define('hello-world', HelloWorld)

It works, but I’m not happy with having all of the HTML markup inside of strings. I want to separate the HTML markup from the JavaScript, preferably in a separate file so that my IDE can give me better support. Here’s an example of how I want to separate them:

<div>
    <div>
        <div id="inner-div"></div>
    </div>
</div>
class HelloWorld extends HTMLElement {
    connectedCallback() {
        const innerDiv = this.getElementById('inner-div')
        innerDiv .textContent = 'Hello World!';
    }
}
customElements.define('hello-world', HelloWorld)

Is it possible to separate them like this?

Advertisement

Answer

There was a way to achieve this in the past, but it was removed from the specification, and subsequently, from browsers as well (e.g. Chrome removed it in Chrome 70). It was called HTML imports and it originally was part of the web components specs.

Currently they are working on a replacement for this obviously lacking platform feature, which will be called HTML modules. Here’s the explainer. Chances are the syntax is going to look similar to this:

  import {content} from "import.html";

Resolving the remaining issues with HTML modules I assume might take quite some time, so until then the only viable option you have is to have either your build stack resolve the issue for you (e.g. with webpack-raw-loader), or to rely on async fetch to get the job done (which might result in a less-than-optimal performance experience).

We already have JSON modules and CSS module scripts (which both were sorely missing features for a long time as well).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement