9

In the tutorials I see only the benefits of Shadow DOM, but there should be drawbacks as well. In which cases should we avoid using Shadow DOM?

ganqqwerty
  • 1,894
  • 2
  • 23
  • 36

2 Answers2

11

Shadow DOM features can be seen as drawback as much as benefits:

Style isolation is a benefit if you want it but a drawback if a user wants to style a component with Shadow DOM from a global CSS stylesheet.

DOM Shadowing is a benefit in some cases, but a drawback if an external script/library or extension needs to parse or select the content.

There are many 3rd party libraries (or extensions) that won't work with Shadow DOM content because they were not designed to deal with it, or need some additional configuration to work with Shadow DOM.

Examples:

Also, extensions that parse HTML will be blocked at the Shadow DOM boundary: a benefit if you don't want to spied, a drawback if you consider them as a useful service.

Event propagation is different inside and outside the Shadow DOM. So you may have some difficulties dealing with UI events.

Example :

Conclusion

  • Use Shadow DOM only if you want CSS style or DOM isolation.

  • Don't use Shadow DOM if you need to interact with some not compliant third party components or library.

Parzival
  • 2,051
  • 4
  • 14
  • 32
Supersharp
  • 29,002
  • 9
  • 92
  • 134
  • There are other ways of isolating CSS (e.g. css modules) that don't cause as much side effects as the Shadow DOM. This can't be the only benefit to the Shadow DOM? – SaroGFX Aug 28 '23 at 07:54
2

Uh, ah, this technology's specification has not stabilized and is not supported by many browsers. I would call that a drawback.

See: https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow

For now I would say; Avoid in most cases, except when you want to experiment with new stuff and it is not for the production environment.

UPDATE: By now all modern browsers support this feature.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33