2

According to MDN the HTML import feature is not supported by Firefox and has to be considered obsolete since Chrome 73 (don't care about other browsers and neither about older versions of Chrome and Firefox).

I'd like to try out web components. I currently have:

  1. a Javascript file defining my class that extends an HTMLElement
  2. an HTML file containing a <template> for my component

How am I supposed to bundle the two pieces and reuse them on different HTML pages?

Since I cannot import HTML, I suppose the only thing left is to import a Javascript. However, I'm not sure about how deal with it.

I know I can use document.createElement() in my Javascript, and create my template programmatically, but I would like to avoid it, if possible. Writing Javascript to get HTML seems stupid to me, unless there is a valid reason to do otherwise.

Another option I see is to write my HTML template as the innerHTML of some node I create in my Javascript. But it does not sound so clean.

Am I missing something? Which is the recommended way to import web components?

Thanks in advance

Community
  • 1
  • 1
leonixyz
  • 1,130
  • 15
  • 28
  • do you have a server behind your "different HTML pages" ? or is it only static pages ? – gui3 Nov 26 '19 at 13:21
  • Static pages, but this shouldn't make any difference. HTTP is just HTTP, and here we are on the client side. So, even though there is a server with lots of middleware involved, there shouldn't be any difference – leonixyz Nov 26 '19 at 13:30
  • i just wanted to point that if you want to use templates the best way i know is from server side (ejs or frameworks like react). – gui3 Nov 26 '19 at 13:37
  • ok thanks but I was referring to [these templates](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots) – leonixyz Nov 26 '19 at 13:43
  • ** to reuse the same markup structures repeatedly on a web page**, seems like they speak of a single page – gui3 Nov 26 '19 at 14:00
  • Yes, in which case my question would not apply. But since I need to reuse my components in _many_ web pages, I'm looking for a straightforward way to import them in many pages. I don't want to copy-paste my template to all pages where I want to reuse my web component – leonixyz Nov 26 '19 at 14:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203120/discussion-between-leonixyz-and-gui3). – leonixyz Nov 26 '19 at 16:04

0 Answers0