Babylon Viewer HTML DOM Element and Shadow Dom

Hi All,

I am trying to put the babylon viewer inside a custom html element. I can’t seem to get it working. Here is my attempt: https://codepen.io/brianteheng/pen/BaWxXxJ

Any insight would be helpful!

Thank you,
-Brian

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Test Shadow Element</title>
  <script src="js/shadow_babylon.js" defer></script>

</head>

<body>
  <h1>Shadow Component</h1>

  <div>
    <my-comp></my-comp>
  </div>

</body>

</html>
````Preformatted text`

shadow_babylon.js:
class CustomElement extends HTMLElement {

    constructor() {

      super();

      // Create a shadow root

      const shadow = this.attachShadow({ mode: 'open' });

    

      const script = document.createElement('script');

      script.src = "https://cdn.babylonjs.com/viewer/babylon.viewer.js";

      script.onload = function () {

        console.log("Script loaded and ready");  

      };

      shadow.appendChild(script);

      const babylon = document.createElement('babylon');

      babylon.setAttribute('model', "https://models.babylonjs.com/boombox.glb");

      babylon.setAttribute("id", "babylon-viewer");

      shadow.appendChild(babylon);  

     

    } 

  }  

  customElements.define('my-comp', CustomElement);

adding @RaananW

Would be great to see that working (or, well, not working) in a live example. From seeing the code I don’t have a very good logical explanation, because I am missing some context.

A quick suggestion - init the viewer yourself using javascript, and only create the element after the script was loaded.

Hi RaananW! I was hoping to get your attention.

Was the codepen link above not working?

I was able to get it working without shadow Dom and using your idea of initializing the viewer. But with Shadow Dom I can’t seem to get it to work

Well, i completely ignored the fact that you totally put a wonderful codepen there. Sorry…

The issue here is that querySelector is running on the document and not on the shadow element. the shadow element will return the babylon element, but the document doesn’t. So the only way to do that is to init using js:

A Pen by Raanan Weber (codepen.io)

2 Likes

That works!

Thank you,
-Brian