Reputation: 17864
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?
Upvotes: 819
Views: 2185386
Reputation: 83
<!-- another-html-file.html -->
<h1>Another HTML file</h1>
Script tag will be replaced in place with the content of another-html-file.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(() => {
const thisScript = document.currentScript
fetch('./another-html-file.html')
.then(
(res) => (
res.ok // checking if response is ok
? res.text() // return promise with file content as string
: null // return null if file is not found
)
)
.then(
(htmlStr) => (
htmlStr // checking if something is returned
? thisScript.replaceWith(
// replace this script tag with the DOM Node created from string
document.createRange().createContextualFragment(htmlStr)
)
: thisScript.remove() // fallback to remove script if null is returned
)
)
})()
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Another HTML file</h1>
</body>
</html>
Upvotes: 0
Reputation: 447
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
Upvotes: 29
Reputation: 2222
With ECMAScript 6 (ES6) you can make this work even without a web server, so you can just open the website directly from your local hard drive. The html would have to be written in a .js file as javascript. First, the html file:
<!--index.html-->
<div id="import_html_here"></div>
<script src="external-html.js"></script>
<script>document.getElementById('import_html_here').innerHTML = htmlToImport;</script>
Then the imported html:
// external-html.js
// a multiline template literal is delimited by backticks:
htmlToImport = `
<a>
<i>home</i>
</a>
`;
Upvotes: 1
Reputation: 92347
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>
(stackoverflow snippet will work better (load full pages, not only message) when you first go here and push button to give your computer temporary acces to cors-anywhere)
Upvotes: 8
Reputation: 10055
No need for jQuery... Here is my solution, I have an external HTML file containing some JavaScript as well which is required to be executed.
I have some code snipped that is integrated as a "widget" in another web application. I test the "widget" within a mock website. It's used in a test environment.
I personally would refrain from doing something like this in a production environment and would rather use a framework such as Angular or React.
main.html
<div id="plugin"></div>
<script>
void async function () {
const htmlFile = await fetch('plugin.html');
const plugin = document.getElementById('plugin');
plugin.innerHTML = await htmlFile.text();
const scriptElements = Array.from(plugin.getElementsByTagName('script'));
for (const scriptElement of scriptElements) {
const newScriptElement = document.createElement('script');
newScriptElement.text = scriptElement.text;
if (!!scriptElement.src) {
newScriptElement.src = scriptElement.src;
}
plugin.appendChild(newScriptElement);
scriptElement.remove();
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => resolve(), 2000);
newScriptElement.onload = () => {
clearTimeout(timeout);
resolve();
};
});
}
} ()
</script>
plugin.html
<style>
#map { height: 500px; }
</style>
<div id="map"></div>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
let map = L.map('map').setView([22.31, 114.17], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: `© <a href="http://www.openstreetmap.org/copyright">
OpenStreetMap</a>`
}).addTo(map);
</script>
Source: https://gist.github.com/moosetraveller/6a3a029287b8aa3621d23d84962f6f1a
Caveat: If your injected script uses document.write
, your document may disappear as it does not write out to where it was intended to.
If you just want to add HTML without JavaScript content:
<div id="plugin"></div>
<script>
void async function () {
const htmlFile = await fetch('plugin.html');
const plugin = document.getElementById('plugin');
plugin.innerHTML = await htmlFile.text();
} ()
</script>
Upvotes: 0
Reputation: 160
Technically this doesn't include an HTML file, but it will let you use HTML syntax in a JavaScript file and import that. Many code editors (including VS Code) can also format it as HTML.
Main HTML file:
<script src="./include.js"></script>
<div id="include-here"></div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const element = document.querySelector('#include-here')
element.innerHTML = html
})
</script>
include.js:
const html = `
<body>
<p>here</p>
</body>
`
You can rename 'include.js' to 'include.html' and it should work the same. Many code editors will then format the file as HTML (else you can manually tell the browser to format it as HTML).
Upvotes: 0
Reputation: 51
Whatever method you choose please check that it works for all relevant browsers. This method listed at w3schools passes the test with these browsers:
You can improve that and put the javascript in a separate file:
<head>
<script src='include_html.js'></script>
</head>
<body>
<div w3-include-html="your_content.html"></div>
<script>
includeHTML();
</script>
</body>
Upvotes: 0
Reputation: 419
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!
Upvotes: 5
Reputation: 2760
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
.
Upvotes: 230
Reputation: 7948
w3.js is pretty cool.
https://www.w3schools.com/lib/w3.js
and we are focus
but consider the below case
- 🧾 popup.html
- 🧾 popup.js
- 🧾 include.js
- 📂 partials
- 📂 head
- 🧾 bootstrap-css.html
- 🧾 fontawesome-css.html
- 🧾 all-css.html
- 🧾 hello-world.html
<!-- popup.html -->
<head>
<script defer type="module" src="popup.js"></script>
<meta data-include-html="partials/head/all-css.html">
</head>
<body>
<div data-include-html="partials/hello-world.html"></div>
</body>
<!-- bootstrap-css.html -->
<link href="https://.../[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- fontawesome-css.html -->
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
<!-- all-css.html -->
<meta data-include-html="bootstrap-css.html">
<meta data-include-html="fontawesome-css.html">
<!--
If you want to use w3.js.include, you should change as below
<meta w3-include-html="partials/head/bootstrap-css.html">
<meta w3-include-html="partials/head/fontawesome-css.html">
Of course, you can add the above in the ``popup.html`` directly.
If you don't want to, then consider using my scripts.
-->
<!-- hello-world.html -->
<h2>Hello World</h2>
// include.js
const INCLUDE_TAG_NAME = `data-include-html`
/**
* @param {Element} node
* @param {Function} cb callback
* */
export async function includeHTML(node, {
cb = undefined
}) {
const nodeArray = node === undefined ?
document.querySelectorAll(`[${INCLUDE_TAG_NAME}]`) :
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`)
if (nodeArray === null) {
return
}
for (const node of nodeArray) {
const filePath = node.getAttribute(`${INCLUDE_TAG_NAME}`)
if (filePath === undefined) {
return
}
await new Promise(resolve => {
fetch(filePath
).then(async response => {
const text = await response.text()
if (!response.ok) {
throw Error(`${response.statusText} (${response.status}) | ${text} `)
}
node.innerHTML = text
const rootPath = filePath.split("/").slice(0, -1)
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`).forEach(elem=>{
const relativePath = elem.getAttribute(`${INCLUDE_TAG_NAME}`) // not support ".."
if(relativePath.startsWith('/')) { // begin with site root.
return
}
elem.setAttribute(`${INCLUDE_TAG_NAME}`, [...rootPath, relativePath].join("/"))
})
node.removeAttribute(`${INCLUDE_TAG_NAME}`)
await includeHTML(node, {cb})
node.replaceWith(...node.childNodes) // https://stackoverflow.com/a/45657273/9935654
resolve()
}
).catch(err => {
node.innerHTML = `${err.message}`
resolve()
})
})
}
if (cb) {
cb()
}
}
// popup.js
import * as include from "include.js"
window.onload = async () => {
await include.includeHTML(undefined, {})
// ...
}
<!-- popup.html -->
<head>
<link href="https://.../[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
</head>
<body>
<h2>Hello World</h2>
</body>
Upvotes: 2
Reputation: 69
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>
Upvotes: 2
Reputation: 113
Using just HTML it is not possible to include HTML file in another HTML file. But here is a very easy method to do this. Using this JS library you can easy do that. Just use this code:
<script> include('path/to/file.html', document.currentScript) </script>
Upvotes: 1
Reputation: 775
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" -->
Upvotes: 50
Reputation: 1178
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>
Upvotes: 31
Reputation: 337
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)
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>
Upvotes: 6
Reputation: 786
I came to this topic looking for something similar, but a bit different from the problem posed by lolo. I wanted to construct an HTML page holding an alphabetical menu of links to other pages, and each of the other pages might or might not exist, and the order in which they were created might not be alphabetical (nor even numerical). Also, like Tafkadasoh, I did not want to bloat the web page with jQuery. After researching the problem and experimenting for several hours, here is what worked for me, with relevant remarks added:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
<meta name="Author" content="me">
<meta copyright="Copyright" content= "(C) 2013-present by me" />
<title>Menu</title>
<script type="text/javascript">
<!--
var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
var dat = new Array();
var form, script, write, str, tmp, dtno, indx, unde;
/*
The "F000" and similar variables need to exist/be-declared.
Each one will be associated with a different menu item,
so decide on how many items maximum you are likely to need,
when constructing that listing of them. Here, there are 20.
*/
function initialize()
{ window.name="Menu";
form = document.getElementById('MENU');
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = str.substr(tmp);
script = document.createElement('script');
script.type = 'text/javascript';
script.src = str + ".js";
form.appendChild(script);
}
/*
The for() loop constructs some <script> objects
and associates each one with a different simple file name,
starting with "000.js" and, here, going up to "019.js".
It won't matter which of those files exist or not.
However, for each menu item you want to display on this
page, you will need to ensure that its .js file does exist.
The short function below (inside HTML comment-block) is,
generically, what the content of each one of the .js files looks like:
<!--
function F000()
{ return ["Menu Item Name", "./URLofFile.htm", "Description string"];
}
-->
(Continuing the remarks in the main menu.htm file)
It happens that each call of the form.appendChild() function
will cause the specified .js script-file to be loaded at that time.
However, it takes a bit of time for the JavaScript in the file
to be fully integrated into the web page, so one thing that I tried,
but it didn't work, was to write an "onload" event handler.
The handler was apparently being called before the just-loaded
JavaScript had actually become accessible.
Note that the name of the function in the .js file is the same as one
of the pre-defined variables like "F000". When I tried to access
that function without declaring the variable, attempting to use an
"onload" event handler, the JavaScript debugger claimed that the item
was "not available". This is not something that can be tested-for!
However, "undefined" IS something that CAN be tested-for. Simply
declaring them to exist automatically makes all of them "undefined".
When the system finishes integrating a just-loaded .js script file,
the appropriate variable, like "F000", will become something other
than "undefined". Thus it doesn't matter which .js files exist or
not, because we can simply test all the "F000"-type variables, and
ignore the ones that are "undefined". More on that later.
The line below specifies a delay of 2 seconds, before any attempt
is made to access the scripts that were loaded. That DOES give the
system enough time to fully integrate them into the web page.
(If you have a really long list of menu items, or expect the page
to be loaded by an old/slow computer, a longer delay may be needed.)
*/
window.setTimeout("BuildMenu();", 2000);
return;
}
//So here is the function that gets called after the 2-second delay
function BuildMenu()
{ dtno = 0; //index-counter for the "dat" array
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = "F" + str.substr(tmp);
tmp = eval(str);
if(tmp != unde) // "unde" is deliberately undefined, for this test
dat[dtno++] = eval(str + "()");
}
/*
The loop above simply tests each one of the "F000"-type variables, to
see if it is "undefined" or not. Any actually-defined variable holds
a short function (from the ".js" script-file as previously indicated).
We call the function to get some data for one menu item, and put that
data into an array named "dat".
Below, the array is sorted alphabetically (the default), and the
"dtno" variable lets us know exactly how many menu items we will
be working with. The loop that follows creates some "<span>" tags,
and the the "innerHTML" property of each one is set to become an
"anchor" or "<a>" tag, for a link to some other web page. A description
and a "<br />" tag gets included for each link. Finally, each new
<span> object is appended to the menu-page's "form" object, and thereby
ends up being inserted into the middle of the overall text on the page.
(For finer control of where you want to put text in a page, consider
placing something like this in the web page at an appropriate place,
as preparation:
<div id="InsertHere"></div>
You could then use document.getElementById("InsertHere") to get it into
a variable, for appending of <span> elements, the way a variable named
"form" was used in this example menu page.
Note: You don't have to specify the link in the same way I did
(the type of link specified here only works if JavaScript is enabled).
You are free to use the more-standard "<a>" tag with the "href"
property defined, if you wish. But whichever way you go,
you need to make sure that any pages being linked actually exist!
*/
dat.sort();
for(indx=0; indx<dtno; indx++)
{ write = document.createElement('span');
write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] +
"', 'Menu');\" style=\"color:#0000ff;" +
"text-decoration:underline;cursor:pointer;\">" +
dat[indx][0] + "</a> " + dat[indx][2] + "<br />";
form.appendChild(write);
}
return;
}
// -->
</script>
</head>
<body onload="initialize();" style="background-color:#a0a0a0; color:#000000;
font-family:sans-serif; font-size:11pt;">
<h2>
MENU
<noscript><br /><span style="color:#ff0000;">
Links here only work if<br />
your browser's JavaScript<br />
support is enabled.</span><br /></noscript></h2>
These are the menu items you currently have available:<br />
<br />
<form id="MENU" action="" onsubmit="return false;">
<!-- Yes, the <form> object starts out completely empty -->
</form>
Click any link, and enjoy it as much as you like.<br />
Then use your browser's BACK button to return to this Menu,<br />
so you can click a different link for a different thing.<br />
<br />
<br />
<small>This file (web page) Copyright (c) 2013-present by me</small>
</body>
</html>
Upvotes: 0
Reputation: 5156
I strongly suggest AngularJS's ng-include
whether your project is AngularJS or not.
<script src=".../angular.min.js"></script>
<body ng-app="ngApp" ng-controller="ngCtrl">
<div ng-include="'another.html'"></div>
<script>
var app = angular.module('ngApp', []);
app.controller('ngCtrl', function() {});
</script>
</body>
You can find CDN (or download Zip) from AngularJS and more information from W3Schools.
Upvotes: 0
Reputation: 7759
I have one more solution to do this
Using Ajax in javascript
here is the explained code in Github repo https://github.com/dupinder/staticHTML-Include
basic idea is:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='main.js'></script>
</head>
<body>
<header></header>
<footer></footer>
</body>
</html>
main.js
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
Upvotes: 2
Reputation: 4773
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>
`);
Upvotes: 200
Reputation: 235
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
Upvotes: 7
Reputation: 390
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.
Upvotes: 2
Reputation: 645
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
Upvotes: 17
Reputation: 2293
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>
Upvotes: 7
Reputation: 2708
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>
Upvotes: 7
Reputation: 13047
Using ES6 backticks ``: template literals!
let nick = "Castor", name = "Moon", nuts = 1
more.innerHTML = `
<h1>Hello ${nick} ${name}!</h1>
You collected ${nuts} nuts so far!
<hr>
Double it and get ${nuts + nuts} nuts!!
`
<div id="more"></div>
This way we can include html without encoding quotes, include variables from the DOM, and so on.
It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:
let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);
https://caniuse.com/#feat=template-literals
Upvotes: 1
Reputation: 139
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>
Upvotes: 11
Reputation: 2182
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 :)
Upvotes: 9
Reputation: 3205
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>
Upvotes: 13
Reputation: 101
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)
Upvotes: 5
Reputation: 17864
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.
Upvotes: 834