Time to see an HTML Import in action! Let's say we want to reuse this little greeting among multiple pages:
<!-- web/greeting.html --> <div> <h1>Hello, imported world!</h1> </div>
Now, insert it, for example, at the end of the body on this page (the following code). Note that CORS rules apply to imported HTML documents just as we saw in Chapter 3, The Power of HTML5 with Dart:
<!-- web/index.html --> <html> <head> <!-- Polyfill for browsers not supporting Web Components. --> <script src="packages/web_components/webcomponents.js"> </script> <link id="linkedCont" rel="import" href="greeting.html"> <script type="application/dart" src="main.dart"></script> <script src="packages/browser/dart.js"></script> </head> <body> <!-- Insert greeting here. --> </body> </html>
This HTML just loads our greeting into a separate DOM tree. To append its content into our page, we need to write some Dart code:
// web/main.dart import 'dart:html'; void main() { LinkElement cont = document.querySelector('#linkedCont'), // Notice that we can select any DOM element and clone // only it and its subtree (true = deep copy). var cloned = cont.import.querySelector('div').clone(true); document.body.append(cloned); }
LinkElement
has the import
property, which is an instance of the Document
class itself, just like the top-level document
variable from the dart:html
package. Then, select div
from the imported document, clone it, and append it to the page.
Let's see the structure this created in the browser:
This is what we expected. The linked greeting.html
HTML document has it's own DOM subtree that we can access through the import
property, and then clone what we want.
We can modify greeting.html
and add some CSS styles to it:
<!-- web/greeting.html --> <style> h1 { color: red; } h2 { color: green; } </style> <div> <h1>Hello, imported world!</h1> </div>
Also, add another heading inside the body of our page:
<body> <h2>Greeting here</h2> <!-- Insert greeting here --> </body>
Then, let's see what happens:
Although we cloned just the div
element containing the <h1>
heading, styles from the linked HTML document are applied to all HTML elements on the page. This is probably not what we wanted and it shows that just including HTML using the <link>
tag isn't enough. We need to encapsulate included HTML and CSS styles.
We need the Shadow DOM!
3.133.127.37