Re: [cssom] Constructable Stylesheets

On 3/18/2015 5:30 PM, Tab Atkins Jr. wrote:
> Draft spec: http://tabatkins.github.io/specs/construct-stylesheets/
>
> When dealing with Shadow DOM-related things, we've found that the
> existing ways to style a component are somewhat suboptimal.  In
> particular, the standard way to style a component is to insert a
> <style> element into its shadow tree during initialization.  If you
> create a bunch of instances of this component, though, that means you
> have a bunch of identical <style> elements cluttering up your DOM and
> making things more expensive.

I'm guessing the "standard way to style a component" of which you speak is reflected in the code at http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/#toc-separation-hide? In that poorly-designed code, they've baked a style element into a template instead of creating an active, singular style element like they should have.

I think a better proposal would be to expect authors to write code that doesn't create a new style sheet each time a component is generated. They could do that by using techniques that make style sheet-scoping unnecessary: use of prefixed class names, custom element names, custom attributes, and/or namespaces. Examples:

<_ class="example.org:some.class"><content></content></_>→ _[class="example.org:some.class"] { /* styles */ }
<_ example.org="example.org"><content></content></_> → _[example.org] { /* styles */ }
<_ xmlns="http://example.org/"><content xmlns="http://www.w3.org/1999/xhtml"/></_> → @namespace e "http://example.org/"; e|_ { /* styles */ } (HTML as XML)
<_ xmlns="http://example.org/"><content></content></_> → _[xmlns="http://example.org/"] { /* styles */ } (HTML as HTML)

The above examples are written with inter-site component sharing in mind; otherwise, just using unique class names should suffice.

(Given the above, I'm not sure why you'd need style isolation of the shadow DOM or a shadow-piercing combinator. Maybe I'm missing something?)

That said, I do think the style sheet construction API could use an overhaul. I'd automate existing techniques though. Currently, you need this code:

var styleSheet = document.createElement("style");
document.head.appendChild(styleSheet);
styleSheet = styleSheet.sheet;

The following would be easier:

var styleSheet = document.createStyleSheet();

The above would append a style element to the head element and return the style element. The style element would be a CSSOM object instead of a CSSOM host object which would allow code like styleSheet.remove(), styleSheet.textContent.replace(/blue/, "lightblue"), and styleSheet.setAttribute("id", "my.id") to work. (I'm guessing that the reason for the current, disconnected design was the same behind the type attribute: the unrealistic idea that the style element should be an anchor for multiple style language.)

— Patrick

Received on Wednesday, 8 April 2015 07:00:51 UTC