Souvik Basu
Souvik Basu

Reputation: 3139

Web Component: How to listen to Shadow DOM load event?

I want to execute a JavaScript code on load of the Shadow DOM in my custom element. I tried the following code but it did not work

x-component.html:

<template id="myTemplate">
   <div>I am custom element</div>
</template>

<script>
var doc = this.document._currentScript.ownerDocument;
var XComponent = document.registerElement('x-component', {
prototype: Object.create(HTMLElement.prototype, {
  createdCallback: {
    value: function() {
      var root = this.createShadowRoot();
      var template = doc.querySelector('#myTemplate');
      var clone = document.importNode(template.content, true);
      clone.addEventListener('load', function(e) {
        alert('Shadow DOM loaded!');
      });
      root.appendChild(clone);
    }
  }
 })
});
</script>

Then I use it in another html as follows - index.html:

<!doctype html>
<html >
<head>
    <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
    <link rel="import" href="x-component.html">
</head>
<body>
    <x-component></x-component>
</body>
</html>

The doc variable is used as I am using Polymer webcomponents.js polyfill and the polyfill needs it.

What is the right syntax to listen to load event of Shadow DOM?

Upvotes: 1

Views: 3220

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

AFAIK, the only way to achieve this is to use MutationObserver:

  attachedCallback: {
    value: function() {
      var root = this.createShadowRoot();
      var template = document.querySelector('#myTemplate');
      var clone = document.importNode(template.content, true);

      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          if(mutation.addedNodes) { // this is definitely a subject to change
            alert('Shadow is loaded');
          };
        });    
      })
      observer.observe(root, { childList: true });
      root.appendChild(clone);
    }
  }

I would be glad to know if there is more elegant way, but for now I use this one.

Live preview: http://plnkr.co/edit/YBh5i2iCOwqpgsUU6En8?p=preview

Upvotes: 2

Related Questions