Web Components have really come a long way since they were first introduced, but one aspect of components that could really change how we code websites is HTML Imports.
This way of working allows us to import HTML documents into other HTML documents. It was possible with Ajax, but HTML Imports is a cleaner method.
HTML Imports are a very new technology and as of the time of writing, are only supported in Chrome 31 and later. Even then, you’re required to activate the feature. To do so you must go to _chrome://flags_ and enable “Enable HTML Imports” then restart chrome and you are ready to go.
Fortunately there is also a Polyfill for HTML Imports which you can find at Github.
Using HTML Imports
If you think about it, we already use imports for our stylesheets and our JS files; this is merely another type of import and the syntax is similar to the way we import stylesheets, in the head of your document place:
<link href="import/post.html" rel="import" />
Getting the content
In order to access the contents of the imported HTML you use:
var post = document.querySelector('link[rel="import"]').import;
This will get the contents of the post.html file we imported into our page, let’s assume the post.html file looks like this:
<article class="post"> <h2>A Post Title</h2> <p><span>Written by: Admin</span></p> <p>If you run a business and want a professional first point of contact or just need a hand with some of the day to day to business tasks because things are getting a bit busy, then we can help.</p> </article>
We now need to get the contents of the page and then select the article and place it on our page:
var post = document.querySelector('link[rel="import"]').import; var article = post.querySelector('.post'); document.body.appendChild(article.cloneNode(true));
We can also take advantage of the template element that is made especially for cases like this and import parts of our template when we feel the need to. The only difference is that in this case we will be importing into a container instead of importing right into the body so that it fits right into our app. It’s all a matter of choice and playing with the JS a little, to insert the HTML into a certain element you would write something like:
var post = document.querySelector('link[rel="import"]').import; var article = post.querySelector('.post'); var clone = document.importNode(article.content, true); document.querySelector('#container').appendChild(clone);
As you can see the difference in this case is that instead of just pasting the HTML into our body we first cloned it and then appended it to an element.
HTML Imports offer us a great way to build better websites and organize applications, it has an easy api to manipulate and once browser support is more wide spread expect it to be a common technique.