Search code examples
javascriptpolymershadow-dompolymer-2.x

How to create a component without using the Shadow DOM?


I am trying to create a component that does not have a Shadow DOM. Yeah, I know, Shadow DOM is great and all and is one of the main focuses of Web Components. But, let's say I wanted a component's styles to inherit from a parent.

With Shadow DOM

<dom-module id="my-view1">
  <template>
    <div class="card">
      <div class="circle">1</div>
      <h1>View One</h1>
      <p>Ut labores minimum atomorum pro. Laudem tibique ut has.</p>
      <p>Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Cu mei vide viris gloriatur, at populo eripuit sit.</p>
    </div>
  </template>
  <script>
    class MyView1 extends Polymer.Element {
      static get is() { return 'my-view1'; }
    }
    window.customElements.define(MyView1.is, MyView1);
  </script>
</dom-module>

I have applied the instructions provided by the Polymer group, to not use a Shadow DOM, at: https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom

But, if I were to not specify a template or specify static get template() { return false; }, the DOM doesn't even load the elements in the Custom Component.


Solution

  • As you said, and as you know :

    "Yeah, I know, Shadow DOM is great and all and is one of the main focuses of Web Components."

    you used the word inherit, and one great thing about shadow-dom's is that inherited text styles will leak inside the shadows..

    for instance :

    <style>
      p { font-size: 1.3em }
    </style>
    <p><your-element></your-element></p>
    

    if you didn't override the text styles in your-element they will inherit the font-size property outer style.

    if you really want to share styles between your elements, we use the include attribute for the style tag in a dom-module template. For instance,

    <dom-module id="french-fries-styles">
      <template>
        <style>
          .french-fries {
            display: block;
            width: 100px;
            height: 30px;
            background-color: yellow; /* french fries are yellow */
          }
        </style>
      </template>
    </dom-module>
    
    <dom-module id="french-fries-are-tasty">
      <style include="french-fries-styles"></style>
      <div class="french-fries"></div>
    </dom-module>
    
    <dom-module id="burger-king">
      <style include="french-fries-styles"></style>
      <div id="burger-king-fries" class="french-fries"></div>
    </dom-module>