I think shadow DOM lets us achieve style encapsulation and also hiding HTML implementation of the component.
But when I inspect shadow root in chrome I can see the HTML of the component.
So what exactly does it help us to achieve? Is it only style encapsulation?
Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.
First off, it's true that shadow DOM can improve style performance, so our theory about style encapsulation holds up. However, ID and class selectors are fast enough that actually it doesn't matter much whether shadow DOM is used or not – in fact, they're slightly faster without shadow DOM.
Shadow DOM refers to the ability of the browser to include a subtree of DOM elements into the rendering of a document, but not into the main document DOM tree. Shadow DOM enables encapsulation. With Shadow DOM, a component can have its own “shadow” DOM tree that cannot be accidentally accessed from the main document.
Shadow DOM is like a parallel DOM tree hosted inside a component (an HTML element, not to be confused with Angular components), hidden away from the main DOM tree. No part of the application has access to this shadow DOM other than the component itself.
Sure, the DevTools allow you to investigate the shadow DOM but if you get the HTML for index.html
querySelector('body').innerHTML
the shadow DOM of the elements is not included.
You explicitly need to switch to the shadow DOM of a custom element to get access to that HTML.
Shadow DOM is not about hiding your elements implementation from other developers, it's about hiding it from CSS, JS or other means that might accidentally read or manipulate it.
This allows to break down complexity of the DOM of a whole application to smaller parts that are better manageable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With