2

With the HTML web components, I understand I can set their HTML code with:

this.innerHTML = `<h1></h1>`;

The problem I have with this is I miss out on the convenience of Emmet Abbreviation and if I'm making a lot of components, this slows me down.

I need a function which returns the HTML file as a string so I can make it equal to the innerHTML like this:

this.innerHTML = getHTML("myfile.hmtl");

How can this be done?

Darryl Johnson
  • 646
  • 6
  • 14

1 Answers1

3

You can do it with fetch().

Note that it's an asynchronous function so you should use async/await or Promise().

this.innerHTML = await fetch( 'myfile.html' ).then( s => s.text() )

2 implementation examples for Web Components:

Supersharp
  • 29,002
  • 9
  • 92
  • 134
  • Note, this will fetch the html file for every instance of the element on the page (as well as parse the HTML for every instance). – morganney Sep 27 '22 at 22:45