HTML Imports

HTML Imports

This is the simplest of the APIs from Web components 🙂

Add a <link rel=”imports” href=”your_html_file”> and all the html/css/js that defines a Web component you plan to use will be imported:

    • It is similar to including CSS in your page!
    • Package your components into an HTML page (can include CSS, JS, etc) and import it!

It is as simple as:

  1. <head>
  2.     <link rel=“imports” href=“components/myComponents.html”>
  3. </head>
  4. <body>
  5.   <my-widget>
  6.     <span slot=“my-title”>Title injected</span>
  7.     <span slot=“my-paragraph”>Paragraph injected</span>
  8.   </my-widget>
  9. </body>

Look at line 2: this is where the importation of the HTML, CSS and JS code of new “components” is done. The HTML+JS+CSS code that defines templates, attachment to a shadow host, CSS, and registering of new custom HTML elements is located in myComponents.html.

You could create a my-widget.html file, add the HTML template and the JavaScript code to that file, and import my-widget.html into your document and use <my-widget>…</my-widget> from the last lesson directly!

External resource

This lesson is a basic introduction to HTML imports. You can add functionality such as onerror and onsuccess callbacks, manage dependencies if you create Web components that use other components and you import the same components more than once, etc. This will interest advanced users who plan to create large libraries of Web components. For creating simple Web components, this lesson explained everything you’ll need for most cases.

Leave a comment