In a previous post I talked about templates - a great way to work with those is using HTML imports. Imports let you reference an external resource to load in, that way you could for example package up your templates in an external .html file and reuse it across your web app.

Setting up an import is very easy and looks similar to what you already do for CSS. 

<link rel="import" href="templates.html">

Note that the rel attribute is set the import and href points to the file you want to import. This file can contain other resources you want to load in (JavaScript, CSS, other HTML imports etc.) so it is a convenient way to share boilerplate code across pages.

You can use onload and onerror to handle the load and error events of an import. For example you would wait for the load event to start cloning any template.

<link rel="import" href="templates.html"
      onload="loadHandler(event)" onerror="errorHandler(event)">

If you have multiple imports and want to know which one loaded or had an error you can access it through the event object:

console.log(event.target.href); // access the href attribute of the link tag

Building on the previous example you could now separate out the template and associated CSS into an external file and load it in with a single line of markup. In the next post I'll talk about creating your own custom elements taking advantage of templates and imports.

Posted
AuthorPeter
CategoriesJavaScript