I want to be able to have an event that calls an asynchronous function that (1) fetches a simple web component and (2) adds the customElement to a container (div id).
Using the fetch API, I haven't had any success. Among a lot of tests I tried to convert "result.text()" to HTML with new DOMParser and a [Object HTML] appears in the targeted container or I tried to convert "result.text()" to a function and I get [Object Promise]...
This is currently my load function
async function load(){
var object = fetch("./src/pages/product.js")
.then(result => result.text())
.then(obj => new Function(obj))
.then(t => console.log(t));
container.innerHTML = object;
}
This is my customElement:
class MyTest extends HTMLElement {
constructor() {
super()
const pElem = document.createElement("p");
pElem.textContent = "Hello from my-test component";
const shadowRoot = this.attachShadow({mode: "open"});
shadowRoot.appendChild(pElem);
}
}
customElements.define("my-test", MyTest);
The expected result is the display of "Hello from my-test component" in the container. How would you do it?
Your help will be very appreciated! Thank you!