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:

JavaScript

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:

JavaScript
JavaScript

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:

JavaScript

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