Imports

HTML Imports gives us a provision to include and load HTML documents within other HTML documents.

html5 imports

Let us say you have a footer.html document with a copyright statement inside a <p> element that you wish to include inside the empty <footer> element of every page.

				
					<p>Copyright © 2019 · All Rights Reserved</p>
				
			

Inside the <head> element of the page where you wish to include footer.html, insert the <link> element with its rel attribute set to import and the href attribute set to the path to footer.html

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

Now if you type the following command in the console, it will output the imported footer.html document including the unwanted <html>, <head> and <body> elements.

				
					document.querySelectorAll('link[rel="import"]')[0].import
				
			

html5 imports browser

To extract just the <p> element including the copyright statement from footer.html, we can chain either another querySelectorAll() method

				
					document.querySelectorAll('link[rel="import"]')[0].import.querySelectorAll("body p")[0]
				
			

or the getElementsByTagName() method to the import property.

				
					document.querySelectorAll('link[rel="import"]')[0].import.getElementsByTagName("p")[0]
				
			

The above selected HTML node is cloned (via the cloneNode() method) and then appended to the <footer> element using the appendChild() method. The JavaScript code is placed inside the load event listener function.

				
					window.addEventListener("load", function() {
						var template = document.querySelectorAll('link[rel="import"]')[0].import.querySelectorAll("body p")[0];
						document.getElementsByTagName("footer")[0].appendChild(template.cloneNode(true));
					}, false);
				
			

HTML Imports in Firefox

Firefox does not support HTML Imports. For HTML Imports to work in Firefox, include either platform.js or webcomponents.js (along with the /src directory and its contents). And instead of the load event, listen to the WebComponentsReady event as shown below

					
						window.addEventListener("WebComponentsReady", function() {
							var template = document.querySelectorAll('link[rel="import"]')[0].import.querySelectorAll("body p")[0];
							document.getElementsByTagName("footer")[0].appendChild(template.cloneNode(true));
						}, false);