Skip to content

Wait for component to be rendered before running some code. #1772

Closed Answered by claviska
PxlCtzn asked this question in Help
Discussion options

You must be logged in to vote

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
});

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@mehrlander
Comment options

Answer selected by PxlCtzn
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
3 participants