New CSS selectors in Web Components
One of the most useful features of the Shadow DOM specification, is scoped CSS. The styles defined in the Shadow DOM don't leak out to the containing page. But within the Shadow DOM you CAN get a sense of the surrounding context of the Custom Element. To make the latter possible, some new selectors have been introduced. In this post, I will explain how I learned about some of these new selectors, focusing on the
In a previous blog posts I focussed on serialising the HTML of the Shadow DOM. But these new CSS selectors should also be transformed and placed in the main document. Because, as long as the Web Component did not load on the client yet, its styles will not show up.
So somehow I needed to transform the selectors from the Shadow DOM styles and move these styles into the main document (or Light DOM). That process taught me quite a lot about how these new selectors work!
A quick recap of serialising the HTML
To serialise the Shadow DOM I go through this process:
- Launch Puppeteer and load a page containing Web Components
- For every Web Component:
- Find the rendered Shadow DOM
- Find the Light DOM contained in the element
- Move the Light DOM into a
- Move the (rendered) Shadow DOM in the place of the Light DOM
- Add a couple of attributes indicating the state of the serialising process
- Add a rehydrate script to the page which will run on the client undoing all the work above