innhold
på jakt etter noen som kan hjelpe deg med en webside?

finn ut hvordan vi kan hjelpe!

It’s common to see Web Components directly compared to framework components. But most examples are actually specific to Custom Elements, which is one piece of the Web Components picture. It’s easy to forget Web Components are actually a set of individual Web Platform APIs that can be used on their own:

In other words, it’s possible to create a Custom Element without using Shadow DOM or HTML Templates, but combining these features opens up enhanced stability, reusability, maintainability, and security. They’re all parts of the same feature set that can be used separately or together.

With that being said, I want to pay particular attention to Shadow DOM and where it fits into this picture. Working with Shadow DOM allows us to define clear boundaries between the various parts of our web applications — encapsulating related HTML and CSS inside a DocumentFragment to isolate components, prevent conflicts, and maintain clean separation of concerns.

How you take advantage of that encapsulation involves trade-offs and a variety of approaches. In this article, we’ll explore those nuances in depth, and in a follow-up piece, we’ll dive into how to work effectively with encapsulated styles.

Why Shadow DOM Exists

Most modern web applications are built from an assortment of libraries and components from a variety of providers. With the traditional (or “light”) DOM, it’s easy for styles and scripts to leak into or collide with each other. If you are using a framework, you might be able to trust that everything has been written to work seamlessly together, but effort must still be made to ensure that all elements have a unique ID and that CSS rules are scoped as specifically as possible. This can lead to overly verbose code that both increases app load time and reduces maintainability.


etc...

Shadow DOM was introduced to solve these problems by providing a way to isolate each component. The and

elements are good examples of native HTML elements that use Shadow DOM internally by default to prevent interference from global styles or scripts. Harnessing this hidden power that drives native browser components is what really sets Web Components apart from their framework counterparts.

Elements That Can Host A Shadow Root

Most often, you will see shadow roots associated with Custom Elements. However, they can also be used with any HTMLUnknownElement, and many standard elements support them as well, including:




  • to




Each element can only have one shadow root. Some elements, including and