About Shadow DOM

Hello!

I continue my cycle of publications about the Web Components group of standards . My goal is to form realistic expectations from this set of technologies, and also, together with you, to come to a clearer understanding of where they should not be applied, and where, on the contrary, nothing better has yet been invented. This time, I suggest dwelling on Shadow DOM in more detail .

, , , . , Shadow DOM - DOM API, , . , , , , , HTML- audio - , #shadow-root - . Shadow DOM audio. , "" , - . UI-, , , . . , , . Shadow DOM, , "?".

Shadow DOM?

  1. . Shadow DOM "", , ( , "") DOM API, , , ( , ID , ).

  2. . Shadow DOM "" DOM- . , Shadow DOM , , - slot. , , - .

, , - ( LitElement), , Shadow DOM - -. . Custom Elements Shadow DOM , , DOM , div. DOM , , CSS- "element.style", , , media- . JavaScript ( , ). Shadow DOM:

let myElement = document.createElement('div');
myElement.attachShadow({
  mode: 'open',
});
myElement.shadowRoot.innerHTML = /*html*/ `
<style>
:host {
  padding: 10px;
}
:host(:hover) {
  color: red;
}
</style>
<slot></slot>
`;

div , . Shadow DOM - :host, , JS. , , , .

Shadow DOM?

, -, - : UI--, -, . , , " " .

Shadow DOM.

, , -, - : .

" ".

?

, Shadow DOM , (, Custom Elements).

Shadow DOM JavaScript, , (SSR) . , .

, CSP (Content Security Policy) - DOM. . innerHTML, insertRule, . , , , - CSP- unsafe-inline. , - . Chromium, adoptedStylesheets. element.style (, , ), Shadow DOM :

let myElement = document.createElement('div');
myElement.attachShadow({
  mode: 'open',
});
myElement.shadowRoot.innerHTML = /*html*/ `
<link rel="stylesheet" href="styles.css">
<slot></slot>
`;

Shadow DOM, , , , , DOM . DOM, .

, , : IE - DOM . , , .

Shadow DOM is a powerful and flexible technology. Its use can greatly facilitate the solution of many problems and opens up scope for creativity in solving atypical problems. But do not expect a magical answer to all your questions from her and a complete absence of difficulties.




All Articles