I have 2 HTML files, suppose a.html and b.html. In a.html I want to include b.html.
In JSF I can do it like that:
<ui:include src="b.xhtml" />
It means that inside a.xhtml file, I can include b.xhtml.
How can we do it in *.html file?
In my opinion the best solution uses jQuery:
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p>This is my include file</p>
This method is a simple and clean solution to my problem.
The jQuery .load() documentation is here.
Expanding lolo's answer, here is a little more automation if you have to include a lot of files. Use this JS code:
$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})
And then to include something in the html:
<div data-include="header"></div>
<div data-include="footer"></div>
Which would include the file views/header.html and views/footer.html.
My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.
In order to get the properly escaped JavaScript file without much work, you can use the following sed command:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js:
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.
Alternatively for browsers that support template literals the following also works:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
Checkout HTML5 imports via Html5rocks tutorial
and at polymer-project
For example:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Shameless plug of a library that I wrote the solve this.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
The above will take the contents of /path/to/include.html and replace the div with it.
No need for scripts. No need to do any fancy stuff server-side (tho that would probably be a better option)
<iframe src="/path/to/file.html" seamless></iframe>
Since old browsers don't support seamless, you should add some css to fix it:
iframe[seamless] {
border: none;
}
Keep in mind that for browsers that don't support seamless, if you click a link in the iframe it will make the frame go to that url, not the whole window. A way to get around that is to have all links have target="_parent", tho the browser support is "good enough".
A simple server side include directive to include another file found in the same folder looks like this:
<!--#include virtual="a.html" -->
Also you can try:
<!--#include file="a.html" -->
A very old solution I did met my needs back then, but here's how to do it standards-compliant code:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
Following works if html content from some file needs to be included:
For instance, the following line will include the contents of piece_to_include.html at the location where the OBJECT definition occurs.
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
Reference: http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
Here is my inline solution:
(() => {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, i => {
let filePath = i.getAttribute('src');
fetch(filePath).then(file => {
file.text().then(content => {
i.insertAdjacentHTML('afterend', content);
i.remove();
});
});
});
})();
<p>FOO</p>
<include src="a.html">Loading...</include>
<p>BAR</p>
<include src="b.html">Loading...</include>
<p>TEE</p>
In w3.js include works like this:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
For proper description look into this: https://www.w3schools.com/howto/howto_html_include.asp
As an alternative, if you have access to the .htaccess file on your server, you can add a simple directive that will allow php to be interpreted on files ending in .html extension.
RemoveHandler .html
AddType application/x-httpd-php .php .html
Now you can use a simple php script to include other files such as:
<?php include('b.html'); ?>
This is what helped me. For adding a block of html code from b.html to a.html, this should go into the head tag of a.html:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Then in the body tag, a container is made with an unique id and a javascript block to load the b.html into the container, as follows:
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
I know this is a very old post, so some methods were not available back then.
But here is my very simple take on it (based on Lolo's answer).
It relies on the HTML5 data-* attributes and therefore is very generic in that is uses jQuery's for-each function to get every .class matching "load-html" and uses its respective 'data-source' attribute to load the content:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
Most of the solutions works but they have issue with jquery:
The issue is following code $(document).ready(function () { alert($("#includedContent").text()); } alerts nothing instead of alerting included content.
I write the below code, in my solution you can access to included content in $(document).ready function:
(The key is loading included content synchronously).
index.htm:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
jquery include plugin on github
You can use a polyfill of HTML Imports (https://www.html5rocks.com/en/tutorials/webcomponents/imports/), or that simplified solution
https://github.com/dsheiko/html-import
For example, on the page you import HTML block like that:
<link rel="html-import" href="./some-path/block.html" >
The block may have imports of its own:
<link rel="html-import" href="./some-other-path/other-block.html" >
The importer replaces the directive with the loaded HTML pretty much like SSI
These directives will be served automatically as soon as you load this small JavaScript:
<script async src="./src/html-import.js"></script>
It will process the imports when DOM is ready automatically. Besides, it exposes an API that you can use to run manually, to get logs and so on. Enjoy :)
Here's my approach using Fetch API and async function
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
To insert contents of the named file:
<!--#include virtual="filename.htm"-->
Another approach using Fetch API with Promise
<html>
<body>
<div class="root" data-content="partial.html">
<script>
const root = document.querySelector('.root')
const link = root.dataset.content;
fetch(link)
.then(function (response) {
return response.text();
})
.then(function (html) {
root.innerHTML = html;
});
</script>
</body>
</html>
Did you try a iFrame injection?
It injects the iFrame in the document and deletes itself (it is supposed to be then in the HTML DOM)
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
Regards
The Athari´s answer (the first!) was too much conclusive! Very Good!
But if you would like to pass the name of the page to be included as URL parameter, this post has a very nice solution to be used combined with:
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
So it becomes something like this:
Your URL:
www.yoursite.com/a.html?p=b.html
The a.html code now becomes:
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
It worked very well for me!
I hope have helped :)
html5rocks.com has a very good tutorial on this stuff, and this might be a little late, but I myself didn't know this existed. w3schools also has a way to do this using their new library called w3.js. The thing is, this requires the use of a web server and and HTTPRequest object. You can't actually load these locally and test them on your machine. What you can do though, is use polyfills provided on the html5rocks link at the top, or follow their tutorial. With a little JS magic, you can do something like this:
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
This will make the link (Can change to be the wanted link element if already set), set the import (unless you already have it), and then append it. It will then from there take that and parse the file in HTML, and then append it to the desired element under a div. This can all be changed to fit your needs from the appending element to the link you are using. I hope this helped, it may irrelevant now if newer, faster ways have come out without using libraries and frameworks such as jQuery or W3.js.
UPDATE: This will throw an error saying that the local import has been blocked by CORS policy. Might need access to the deep web to be able to use this because of the properties of the deep web. (Meaning no practical use)
Use includeHTML (smallest js-lib: ~150 lines)
Loading HTML parts via HTML tag (pure js)
Supported load: async/sync, any deep recursive includes
Supported protocols: http://, https://, file:///
Supported browsers: IE 9+, FF, Chrome (and may be other)
USAGE:
1.Insert includeHTML into head section (or before body close tag) in HTML file:
<script src="js/includeHTML.js"></script>
2.Anywhere use includeHTML as HTML tag:
<div data-src="header.html"></div>
There is no direct HTML solution for the task for now. Even HTML Imports (which is permanently in draft) will not do the thing, because Import != Include and some JS magic will be required anyway.
I recently wrote a VanillaJS script that is just for inclusion HTML into HTML, without any complications.
Just place in your a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
It is open-source and may give an idea (I hope)
You can do that with JavaScript's library jQuery like this:
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
Please note that banner.html should be located under the same domain your other pages are in otherwise your webpages will refuse the banner.html file due to Cross-Origin Resource Sharing policies.
Also, please note that if you load your content with JavaScript, Google will not be able to index it so it's not exactly a good method for SEO reasons.
Web Components
I create following web-component similar to JSF
<ui-include src="b.xhtml"><ui-include>
You can use it as regular html tag inside your pages (after including snippet js code)
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
ui-include { margin: 20px } /* example CSS */
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>
<div>My page data... - in this snippet styles overlaps...</div>
<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>
None of these solutions suit my needs. I was looking for something more PHP-like. This solution is quite easy and efficient, in my opinion.
include.js ->
void function(script) {
const { searchParams } = new URL(script.src);
fetch(searchParams.get('src')).then(r => r.text()).then(content => {
script.outerHTML = content;
});
}(document.currentScript);
index.html ->
<script src="/include.js?src=/header.html">
<main>
Hello World!
</main>
<script src="/include.js?src=/footer.html">
Simple tweaks can be made to create include_once, require, and require_once, which may all be useful depending on what you're doing. Here's a brief example of what that might look like.
include_once ->
var includedCache = includedCache || new Set();
void function(script) {
const { searchParams } = new URL(script.src);
const filePath = searchParams.get('src');
if (!includedCache.has(filePath)) {
fetch(filePath).then(r => r.text()).then(content => {
includedCache.add(filePath);
script.outerHTML = content;
});
}
}(document.currentScript);
Hope it helps!
Here is a great article, You can implement common library and just use below code to import any HTML files in one line.
<head>
<link rel="import" href="warnings.html">
</head>
You can also try Google Polymer
To get Solution working you need to include the file csi.min.js, which you can locate here.
As per the example shown on GitHub, to use this library you must include the file csi.js in your page header, then you need to add the data-include attribute with its value set to the file you want to include, on the container element.
Hide Copy Code
<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>
... hope it helps.
There are several types of answers here, but I never found the oldest tool in the use here:
"And all the other answers didn't work for me."
<html>
<head>
<title>pagetitle</title>
</head>
<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
<frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">
</frameset>
</html>
I am relatively new so I may not have done them right but I have tried them. The closest I got is the code I am including. It was work for awhile but the modals wouldn't "fire". I tried to remedy that and lost my inclusion. So here goes.
HTML
<!--============================================-->
<!-- End of Main Program, Modals Follow -->
<!--============================================-->
<section id="activeModal">
<!--> placeholder for every modal in this project </!-->
<!--> each modal is stored in a separate file (modals.html) </!-->
<!--> main.js builds an include with a js script, appends it here, and it executes (hopefully) </!-->
</section><!-- /activeModal -->
JS
// event listener for modals
$("button").on('click', function() {
for ( i=0; i<this.attributes.length ;i++ ) { // this - identifies the modal sought
if ( this.attributes[i].name === "data-target" ) {
var target = this.attributes[i].value; // get the modal to "fire" (data-target attribute)
};
};
modalId = "modals/"+target.substring(1, target.length)+".html"; // strip the '#' from target
$("#activeModal").empty(); // remove any previous modal information
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
$("#activeModal").append(includeHTML); // append the 'import' html
$(target).modal("show"); // show the modal
});
I am expecting the html for any of about 20 modals to appear in the activeModal <section> of index.html. Then, I have the problem of making them "fire".
Based on this line, it looks like you are trying to use server-side includes on the client-side when a button is clicked.
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
This is quite simply impossible.
You can't trigger a server-side include with client-side code. Server-side includes must be made before the response is sent to the client. To get more data from the server, you will have to initiate another request, perhaps via AJAX.
var stackoverflowResponse = document.createElement("div");
stackoverflowResponse.innerHTML = "Look in the console for the answear";
document.body.replacewith(stackoverflowResponse);
You could try changing the extension of your index.html to .shtml, and then using Server Side Includes to include the content of another file.
<!--#include file="included.html" -->
When I did this, I also believe I had to update the .htaccess file to recognize the .shtml as an index file:
AddType text/html .shtml
AddHandler server-parsed .shtml
AddHandler server-parsed .shtml .html
AddHandler server-parsed .shtml .htm
Well you can try out something like this using jquery:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("xyz.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
As my website has only one page, and the index.html was getting really long and impossible to read. So I decided to put each section in a different HTML file and use jQuery to included it.
I used jQuery's include in the way as it has been mentioned here to include a external HTML file but apparently it doesn't work for my website. I really don't know what is the problem.
Here is the link of my workspace.
Here is what I am doing in index.html file to include other sections
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
I also used this method to make sure the file is accessible and everything was fine. So the problem is not the accessibility of the files
You are overwriting the contents of #includedContent seven times (see documentation of jQuery.load). With AJAX, there is no guarantee which request will complete first so you will end up with random page content inside the container.
The solution is to create containers for each page and load each page inside its dedicated container, something like this:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
NB: Having said all that, I do not understand how AJAX solves the problem of the page being too long/impossible to read.
There are several things that look odd to me:
all your load functions run at document ready, which is weird while having all the same target. load replaces (not adds) the content of the selected element with what is being loaded, you probably are trying to add all the html contents, but your current setup would actually just load page7.html into #includedContent
the paths look strange to me, i guess ./ may cause errors, try to leave out ./ everywhere.
rather than loading an entire html page, you might just want to load a piece of that file (i dont know how pageX.html looks), for example you would not want to load the <html> node entirely, rather the content only: .load('page1.html #content')
are you including jquery correctly? there is no .js in your inclusion
I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})
I'm writing a static web site that uses JQuery to make some AJAX calls to a RESTful API and populate the page with data.
The site functions correctly (and quickly), everything is good.
As I extend the site and add additional pages, I'm noticing that I'm duplicating certain regions on every page.
For instance, each page shares a common header element.
<header>...Some non-trivial content...</header>
Rather than repeat this definition on each page is there some mechanism, by which, I can define this section once and include it in each document.
Remember that the pages must be served statically but any standard complaint browser functionality can be utilised.
Is there a good way to do this, and what is it or, will I have to abandon DRY principles for this aspect of my client side code?
There's definitely some ways to achieve this. You could either do it using some features of your server-side language that allows to include the content of a page in another page, or if you do not have any server-side technology, you could simply put that code in it's own html document and load it's content using AJAX.
In jQuery it could look like:
$('#header').load('header.html');
However, if the content isin't static for all pages, you could always define a JS module that would be responsible to render this header. You module could make use of a client-side templating engine, like Mustache, Handlebars, etc. However you do not have to use any of these.
Here's a simple example:
DEMO
//in somefile.js, please note that you should namespace your modules
var Header = {
//default config
config: {
el: '#header',
title: 'Some title'
},
init: function (config) {
var cfg = this.config = $.extend({}, this.config, config);
$(cfg.el).html('<h1>' + cfg.title + '</h1>');
}
};
$(function () {
Object.create(Header).init({
title: 'Some other title'
});
Object.create(Header).init({
el: '#header1',
title: 'Yeah'
});
});
As I mentioned in the comment, this is how I do it:
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
You could use jQuery's ajax as to load the header file. In each file you could load the html like so:
$('#header').load('header.html');
Since you're already using AJAX calls to populate your site with data, you could do the same for the common regions.
Just store the HTML for those regions in a separate file and load it in the page with AJAX. Also, you can work with caching using the Cache-Control headers on that file so you don't reload the entire content from the server with each page load.
If you're using straight HTML, you could do it with a SSI include command or by creating a template page and including it in jQuery. Both of these links might help you
Include another HTML file in a HTML file
and
http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-Command.htm
It looks like this in modest:
main.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<include>reusablePiece</include>
</head>
<body>
<reusablePiece/>
</body>
</html>
reusablePiece.xml
<header>...Some non-trivial content...</header>
Very simple would be the jQuery .clone() function.
If you have more complex content I recommend looking at Handlebars.js which is a full fledged JS templating engine.