-
tl;dr: Is there a way to tell inline JS to wait for all the components to be rendered before running a piece of code ? Hi every one, Here is the code I wrote: let anchor = window.location.hash
if (anchor !== "") {
let drawer = document.querySelector(`sl-drawer#drawer--${anchor.substring(1)}`)
console.log(drawer)
if (drawer != null) {
drawer.show()
}
} Is there a way to tell inline JS to wait for all the components (thus the targetted drawer) to be rendered before trying to call the show() method on it? PS: I'm not using any framework, just good old plain JS and HTML. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You can always get a reference to the element in the DOM but, as you've discovered, its properties, methods, etc. won't be available until the element is registered. The customElements.whenDefined() function is what you're looking for. customElements.whenDefined('sl-drawer').then(() => {
// <sl-drawer> is registered
});
``
To wait for multiple elements, you can use `Promise.all()`:
```js
Promise.all([
customElements.whenDefined('sl-button'),
customElements.whenDefined('sl-drawer'),
// ...
]).then(() => {
// all elements are registered
}); |
Beta Was this translation helpful? Give feedback.
-
Thank you so much @claviska . |
Beta Was this translation helpful? Give feedback.
You can always get a reference to the element in the DOM but, as you've discovered, its properties, methods, etc. won't be available until the element is registered. The customElements.whenDefined() function is what you're looking for.