Search code examples
javascriptweb-componentshadow-domcustom-elementslot

shadow dom <slot> tag in firefox


Is there a way to make the shadow dom's <slot> element work in firefox?

As a work around i'm currently adding all my content from an object with a for loop and .innerHTML (see below) but this is a rather ugly method.

webcomponents.js is added as first script tag in the head

html

<portfolio-container></portfolio-container>

js

const allContent = [{
        title: "hello",
    }, {
        title: "hello",
    }];

for (var i = 0; i < allContent.length; i++) {
    shadowRoot.innerHTML += "<portfolio-item data-title='"+ allContent[i].title +"'></port-item>";
  }

Solution

  • You can use the a library to polyfill the Shadow DOM "v1" specification that is called shadydom.

    Before using the Sadow DOM API, load the shadydom.min.js file from a <script> element.

    <script src="shadydom.min.js"></script>
    
    <div id="RootDiv">
      <span>Content</span>
    </div>
    
    <script>
       var div = document.querySelector( '#RootDiv' )
       div.attachShadow( { mode: 'open' } )
          .innerHTML = 'Content:<slot></slot>'
    </script>
    

    var div = document.querySelector('#RootDiv')
    div.attachShadow( { mode: 'open' } )
       .innerHTML = 'This is the content:<slot></slot>'
    <head>
        <base href="https://rawgit.com/">
        
        <!--Array.from() polyfill for IE
        <script src="joshuacerbito/d6599f1c4a218e722a03514c3dbff1c2/raw/4c43e6346ca48d66344c9b35fe7381b883ec2b32/array_from_polyfill.js"></script>-->
      
        <!--Shadow DOM polyfill for Firefox and IE-->
        <script src="webcomponents/shadydom/master/shadydom.min.js"></script>
    
    <body>
        <h4>Simple Shady</h4>
        <div id="RootDiv">
          <span>Content</span>
        </div>