Using Shadow DOM

As we want to apply styles from greeting.html only to elements in greeting.html, we'll wrap it with HTML5 Template. As we mentioned earlier in this chapter, everything inside the <template> tag will get parsed into DOM elements but won't be run. This means that styles inside <template> have no effect until we paste them outside of the template:

<!-- web/greeting.html -->
<template>
  <style>
  h1 { color: blue; }
  h2 { color: yellow; }
  </style>
  <h1>Hello, imported world!</h1>
</template>

In order to make it more like a real-world example, we'll add some styles to index.html as well:

<!-- index.html -->
<head>
  <link rel="import" href="greeting.html" id="myElementLink">
  <style>
  h1 { color: red !important }
  h2 { color: green; }
  </style>
</head>
<body>
  <h2>Greeting here</h2>
  <!-- Insert greeting here. -->
  <!-- We'll create Shadow DOM in this element. -->
  <div></div>
</body>

We first colored <h1> red and then blue in the imported HTML. Then, we colored <h2> green and yellow, respectively. The question is, what colors will <h1> and <h2> have inside the body?

Now, let's update the Dart code. Instead of pasting cloned elements from the imported document right into the top-level document body, we'll create a Shadow DOM and paste it inside this new so-called shadow-root:

// web/main.dart
import 'dart:html';

void main() {
  LinkElement cont = document.querySelector('#myElementLink'),
  var template = cont.import.querySelector('template'),
  // Get DOM subtree from the external document,
  // clone it and make it available in the current document.  
  Node clone = template.content.clone(true);
  // Target element where we'll put cloned elements.
  DivElement targetDiv = document.querySelector('body > div'),
  // Create a Shadow DOM in the target element and insert
  // the cloned elements inside the new root.
  ShadowRoot root = targetDiv.createShadowRoot();
  root.append(clone);
}

So, what are the colors of <h1> and <h2> now? Take a look:

Using Shadow DOM

As shown in the preceding screenshot, <h1> is blue. The root document's styles don't apply to it because <h1> is inside the Shadow DOM, which has its own styles, and those color <h1> blue. The logic behind the <h2> color is analogous. Our <div> target, where we placed the cloned DOM subtree from the imported template, has turned into a document itself.

This is nice, but we still have to clone the elements by ourselves; with a more complicated DOM structure, we would have to add classes to the elements that we want to replace with our custom templates. Also, when adding DOM elements dynamically, we have to first add them to the DOM tree and then replace them using Dart, as we did right now.

That's all doable, but it's a bit clumsy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.141.27