Assuming an HTML structure with 2 custom web components <my-component-one> and <my-component-two> using lit that are individually lazy loaded, is it somehow possible to check within one of the components to see if the other has already loaded/rendered/mounted?

So far, my only success is relying on the shadowRoot property, as well as emitting a CustomEvent from the other component's connectedCallback and listening to it;

@customElement('my-component-one')
export class MyComponentOne extends LitElement {
  connectedCallback() {
    super.connectedCallback()
    if (document.querySelector('my-component-two')?.shadowRoot) {
      console.log(' component two mounted, it loaded before component one')
    } else {
      window.addEventListener('my-component-two:mounted', () => {
        console.log(' component two mounted, it loaded after component one')
      })
    }
  }
}

// somewhere within my-component-two's connectedCallback()
this.dispatchEvent('my-component-two:mounted', {
  bubbles: true,
  composed: true
})

Curious if there is a simpler way to achieve this? It would be fantastic if I didn't have to emit a custom event within the other component. I tried variations of document.querySelector('my-component-two').addEventListener('connectedCallback') by trying all lifecycle events as well as verbs like mounted, ready, load|loaded and idle but nothing seems to be natively emitted as far as events I can intercept when lit/web components are loaded.

Thanks everyone.

0

There are 0 best solutions below