Useful tips for using HTML imports (part 1)
Breadcrumb
- Home
- PronovixBlog
- Useful tips for using HTML imports (part 1)
Part 1 of my two-part series about using HTML imports contains the basics and a simple example. We’ll go deeper in part 2.
Have you ever tried including an HTML page inside another HTML document? Before HTML imports, you had to work around this problem using iFrames or AJAX, both pretty inconvenient for the task. HTML imports solves this problem elegantly. It hasn’t been long since I started using it, but I found it such an amazingly useful tool that I wanted to share my experiences with you.
HTML Imports, part of the Web Components cast, is a way to include HTML documents in other HTML documents. You’re not limited to markup either. An import can also include CSS, JavaScript, or anything else an .html file can contain. In other words, this makes imports a fantastic tool for loading related HTML/CSS/JS.
You could use it to:
Example:
:
Implementing Bootstrap is an everyday task for site builders, where imports can come in very handy. I will recap how it was done before HTML imports, then show you a simple example of doing it with HTML imports.
The most common way to implement Bootstrap without HTML imports is to link the Bootstrap files one by one like this:
This is pretty straight forward, but what happens when you add or implement more and more files like this? Your header can get really big and messy.
With imports we can make a links.html file and simply import it into our main document. Neat right?
To include an import on your page declare
. The URL of an import is called an import location. To load content from another domain, the import location needs to be CORS-enabled.
Here is the code for a simple import:
Now your site can use the some_file.html’s resources whenever you need them. To do so you have to use some Javascript.
Note: script and other links are executed automatically and only once. The ‘only once’ part is really important so keep it in mind!
Let’s say this is our import file (let’s call it hello.html):
Hello!
This is a sample page!
Olle!
This is an another content.
And this is the file that calls the import:
You call the link’s .import method and then simply append the resources wherever you need them. Pretty cool right?
Notice that the style section doesn’t need to be fetched, it will be automatically added to the parent window.
This blog post walked you through the basics of using HTML imports. Join me soon for part 2, where I tell you more about using a DOM API and sub imports. I’ll also summarise my findings about dependency management and address some performance questions.
Richárd works as a Front-End Developer at Pronovix.
Articles on devportals, DX and API docs, event recaps, webinars, and more. Sign up to be up to date with the latest trends and best practices.