P粉0943518782023-09-05 00:37:47
Trigger the connectedCallback event on open tag
<editable-h1>
Hello World’s
innerHTML has not been parsed
setTimeout
parsedCallback will use a similar trick under the hood, using
requestAnimationFrame or
MutationObserver (there are many more lines of code) .
setTimeout is a hack, or you don't want to waste that
millisecond using
setTimeout, you can check out Andrea Giammarchi's html- parsed-element code
(Of course it requires loading and parsing, and it also increases dependencies and code complexity, so it takes more time overall)
Need a callback function to execute after the child element changes or parsing is completed
https://github.com/WICG/webcomponents/issues/809
All methods boil down to the same goal: Wait for the event loop to be empty
What is an event loop?https://www.youtube.com/watch?v=8aGhZQkoFbQ
customElements.define("editable-h1", class extends HTMLElement { connectedCallback() { setTimeout(() => { this.innerHTML = `<h1>${this.innerHTML}</h1><button>Edit</button>`; let h1 = this.querySelector("h1"); let button = this.querySelector("button"); button.onclick = (evt) => { button.innerHTML = (h1.contentEditable = !h1.isContentEditable) ? (h1.focus(),"Save") : "Edit"; } }); } });
<editable-h1>Hello World!</editable-h1> <editable-h1>Hello Web Components World!</editable-h1>