Share style across web components “of the same type”

◇◆丶佛笑我妖孽 提交于 2019-12-17 13:29:40

问题


If I understand it correctly, creating an instance of a web component can be summed up as creating a shadow root and copying the markup, e.g. from a template into it:

var Template = document.querySelector('#myTemplate');
var TemplateClone = document.importNode(Template.content,true);
TargetElement.appendChild(TemplateClone);

Of course, if the template contains css rules in a style-tag, those will be copied as well. Thus we can have scoped styles which belong to the internal markup of a web component.

Questions:

  1. Does it have any performance implications when I create tons of instances of the very same web component, as the style is just copied and not reused?
  2. Is there a way to share the style node across multiple instances of the same web component?

回答1:


Does it have any performance implications...?

Yes, it depends on how many instances, and on the CSS engine implemented in the browser. You'll have to test every use case and take in account speed versus memory consumption.

Is there a way to share the style node across multiple instances of the same web component?

Yes, you can use @import url like in this SO question. Or you can choose to not use Shadow DOM and use global CSS style only.

2019 update

As Harshal Patil suggested, since Chrome 73 and Opera 60 it is possible for multiple Shadow DOM to adopt the same stylesheet. This way an update in the stylesheet will be applied to all the web components.

let css = new CSSStyleSheet
css.replaceSync( `div { color: red }` )

customElements.define( 'web-comp', class extends HTMLElement {
    constructor() {
        super()
        let shadow = this.attachShadow( { mode: 'open' } )
        shadow.innerHTML = `<div><slot></slot></div>`
        shadow.adoptedStyleSheets = [ css ]
    }
} )
color.oninput = () => css.replaceSync( `div { color: ${color.value} }` )
<web-comp>Hello</web-comp>
<web-comp>World</web-comp>
<input value=red id=color>


来源:https://stackoverflow.com/questions/42645363/share-style-across-web-components-of-the-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!