HTML5 Imports: Embedding an HTML File Inside Another HTML File

HTML5 Imports: Embedding an HTML File Inside Another HTML File

The <link> element is really a boon. It offers you a simple and declarative way to embed JavaScript and Style sheets in multiple HTML documents, but unfortunately, it doesn’t allow for embedding of HTML files.

To achieve this, you’re required to either use the heavy weight <iframe> element or the JavaScript object XMLHttpRequest that is used in AJAX programming. But now, with the introduction of an exciting technology known as HTML5 Imports, the way how we code our websites has totally changed.

Imports allow you to use the <link> element to import HTML documents into other HTML documents, means you’re now not limited to the <iframe> element or write a bunch of Ajax. An import also has the ability to create a bundle of CSS, JavaScript, and HTML code, which makes it an outstanding tool for loading self-contained components into your HTML documents. This blog post is written with the intention of helping you learn how to implement HTML imports in your future web projects.

Embedding an HTML File Inside Another HTML File

Browser Support

Unfortunately, the browser support for HTML5 imports is still very limited. The implementation of this new and interesting technology was first seen in the 31st version of Google Chrome browser, where you were still required to enable HTML imports manually. To do so, you had to go to chrome://flags (experimental features of Chrome), enable the flag “Enable HTML Imports”, and then re-launch your Chrome.
Enable HTML5 imports

But now you will be very glad to know that Chrome 36 has native support for HTML imports, which means you now don’t need to worry about activating this feature manually. Just implement HTML5 Imports in your documents and Chrome 36 will handle rest.

Additionally, to detect whether a browser has support for HTML5 Imports or not, you can use the function given below:

if ("import" in document.createElement("link")) {
  // This browser supports HTML5 Imports.
}

For other browsers, which don’t support HTML5 Imports, you can make use of Polymer’s Polyfill.

Using HTML Imports

HTML imports make use of the common <link> element to specify the path of a file that you want to load, just like we import scripts and style sheets in the head of your HTML document.

<link rel="stylesheet" href=" styles.css">

For an import, all you need to do is to replace the value of rel attribute with “import”. When you set the rel attribute to import, this tells the browser to import the referenced file into the document.

<head>
<link rel="import" href="import/doc.html">
</head>

Remark: The web address of an import is known as an import location. If you wish to load an HTML document from another domain, you need to make sure the import location is CORS-enabled.

<link rel="import" href="http://xyz.com/one.html">

Getting the Content

When you include an import on a page, it doesn’t mean that the content of that file will automatically be visible in your document. Why? Because the content of the imported document is not the part of the parent document’s DOM tree.

Remark: This rule is applicable only for HTML content. The browser will automatically load any JavaScript and CSS code, and apply it to the main document.

To access the content of an import, you have to write some JavaScript.

var doc= document.querySelector('link[rel="import"]').import;

This will grab all the content of the doc.html file that we’ve imported into our web page. Link element’s .import property remains null, if:

  • The resource is CORS-disabled.
  • The <link> doesn’t have rel="import".
  • HTML Imports are not supported in the browser.
  • Either the <link> has been removed from the DOM or not been added to the DOM.

Let’s assume doc.html contains:

<text class="doc">
<h2>Title of the Document</h2>
<p><span>Author: Ajeet Yadav</span></p>
<p>CreativeWebLogix: Convert Existing Site to Responsive</p>
</text>

Now, we need to get the content of the import and then select the text and clone it into our page.

<body>
<script>
var doc = document.querySelector('link[rel="import"]').import;
// Grab DOM from doc.html's document.
var text = doc.querySelector('.doc');
document.body.appendChild(text.cloneNode(true));
</script>
</body>

That’s all!

Using Templates

Additionally, you can also use HTML Imports in tandem with the <template> element and import sections of markup to use when you need them. In that case, instead of pasting the HTML right into the body, we’ll first create a deep copy of .content of text using document.importNode(), and then import it into a container. So, the code would look something like this:

<script>
var doc = document.querySelector('link[rel="import"]').import;
var text = doc.querySelector('.doc');
var clone = document.importNode(text.content, true);
document.querySelector('#container').appendChild(clone);
</script>

Loading Events

The <link> element has 2 events: onerror (for a failed attempt of loading import) and onload (for a successfully loaded import) that you can use to keep an eye on the loading status of your imports. In order to execute the code after the loading of the import file, and to avoid errors, it’s better to take advantage of onload and onerror attribute.

<script>
// Handle Loaded Imports
functionhandleLoad(event) {
console.log('Loaded import: ' + event.target.href);
}

// Handle Errors.
functionhandleError(event) {
console.log('Error loading import: ' + event.target.href);
}
</script>
<link rel="import" href="doc.html" onload="handleLoad(event)" onerror="handleError(event)">

Remark: The browser loads the import file immediately after encountering the <link> element. Therefore, make sure to define your event handlers before the <link> tag in your markup. Otherwise, you may get console errors for undefined functions.

And, if you’ve created the import dynamically, then:

var link = document.createElement('link');
link.rel = 'import';
link.href = 'doc.html'
link.onload = function(event) {...};
link.onerror = function(event) {...};
document.head.appendChild(link);

Bundling Resources

As I mentioned earlier, Imports are quite useful for bundling HTML, CSS, and JavaScript into a single deliverable. Below, I’m showing you a real-world example of Bootstrap that is comprised of numerous <link> and <script> elements.

<head>
<link rel="import" href="bootstrap.html">
</head>

When you import bootstrap.html into your HTML document, the browser first load each of the following CSS and JavaScript files and subsequently apply them to the main document.

<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="fonts.css">
<script src="bootstrap.js"></script>
<script src="jquery.js"></script>
<script src="bootstrap-dropdown.js"></script>
<script src="bootstrap-tooltip.js"></script>

Conclusion

Thanks to HTML5 imports! You’re now able to create reusable content that others can consume and bring in their projects with a simple line of code i.e. <link rel="import">. This extremely powerful technology has totally changed the world of front-end web development. Embedding an HTML source inside another was not so easy to do, until HTML Imports came into existence.

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.