Can you link to an HTML file? - html

My website has the same navigation menu throughout, instead to rewriting the HTML code for every page, can I link to a second HTML file (that contains the nav HTML code) like you would with CSS? Or will that create problems?

Simple way would be to put the header part in a separate html file.
Now load this file in html code using jQuery load function like
$("#headerDiv").load("header.html")
Know that, this will require web server because load function sends a request to server.
Check out the code sample:
demo.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function(){
$("#headerDiv").load("header.html");
});
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>
header.html
<div >
<a>something</a>
<a>something</a>
</div>

That is called HTML includes, and YES, it is possible
<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
NOTES
HTML doesn't have a simple include mechanism (except for frames like iframe, which have side effects).
A better solution would be to use Server-Side includes, which is the preferred way of adding common parts to your document, on the server, of course.

for an HTML solution -since you have no other tags in your question- there is HTML imports:
<link rel="import" href="nav.html">
But this new -working draft- and it doesn't have good browser support.
Resources:
W3C - imports
MDN - HTML Imports
caniuse - HTML Imports
webcomponents.org - introduction to html imports
html5rocks - imports

W3schools has an include. They also have there own CSS as a side note. Put the callup in footer (wherever)
<script src="vendor/w3js.min.js"></script>
<script src="w3.includeHTML();"></script>
And then on page:
<header class="header navbar-fixed-top">
<nav id="inc_nav" w3-include-html="nav.html"></nav>
</header>
<section id="inc_header" w3-include-html="header.html"></section>
<div id="content" tabindex="-1"></div>

Related

Is it possible to automatically render the header and footer on all pages?

DISCLAIMER: I'm a complete newbie to programming. I've my experiences with editing code through trial and error, but I do not have any real knowledge.
I'm looking to build a website from scratch. How do I make it so that I don't have to paste the same header/footer code to every page? I'd assume that there is a designated file for the header/footer; on the pages which I want to include the header/footer, I would have to include a line of code to call it?
Also found this similar question/topic/thread: Use same header and footer on all webpages
if you are looking to do it using just Html there is no possible way, but you can use JavaScript inside your html to create a custom attribute which will include your html files. You can read more about it here - template tag examples
This is not the best solution for this, I won't personally recommend you to do this as you are a beginner.
This might be overwhelming at first but you don't need to understand or learn it right now. For a quick example -
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test File</title>
</head>
<body>
<div include-your-html = "header.html">
<!--Cosidering I have header.html file in the same directory-->
<p>This is my body</p>
<div include-your-html = "footer.html">
<!--Cosidering I have footer.html file in the same directory-->
<!--You can use this script to set the attribute-->
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("include-your-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
elmnt.removeAttribute("include-your-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
includeHTML()
</script>
</body>
</html>
For some of the people this may be blocked due to CORS policy, you can set up a CORS proxy to get around this. More detailed information at sideshowbarker's answer here

How to include header/footer in a static website? [duplicate]

I want to create common header and footer pages that are included on several html pages.
I'd like to use javascript. Is there a way to do this using only html and JavaScript?
I want to load a header and footer page within another html page.
You can accomplish this with jquery.
Place this code in index.html
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
and put this code in header.html and footer.html, at the same location as index.html
click here for google
Now, when you visit index.html, you should be able to click the link tags.
I add common parts as header and footer using Server Side Includes. No HTML and no JavaScript is needed. Instead, the webserver automatically adds the included code before doing anything else.
Just add the following line where you want to include your file:
<!--#include file="include_head.html" -->
Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?
If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php
<?php include('header.php'); ?>
Do the same in the footer of each page to include the content from your footer.php file
<?php include('footer.php'); ?>
No JavaScript / Jquery or additional included files required.
NB You could also convert your .html files to .php files using the following in your .htaccess file
# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
You could also put: (load_essentials.js:)
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
I tried this:
Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.
I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.
JS Function
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
Get the content
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
index.html
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
views/header.html
<!-- This element will replace #header -->
<header id="new-header"></header>
The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page
The question asks about using only HTML and JavaScript. The problem is that a second request to the server using JavaScript or even jQuery (requesting the extra header.html "later") is:
Slow!
So, this is unacceptable in a production environment. The way to go is to include only one .js file and serve your HTML template using only this .js file. So, in your HTML you can have:
<script defer src="header.js"></script>
<header id="app-header"></header>
And then, in your header.js put your template. Use backticks for this HTML string:
let appHeader = `
<nav>
/*navigation or other html content here*/
</nav>
`;
document.getElementById("app-header").innerHTML = appHeader;
This has also the benefit, that you can change the content of your template dynamically if you need! (If you want your code clean, my recommendation is not to include any other code in this header.js file.)
Explanation about speed
In the HTTP/2 world, the web server "undestands" what additional files (.css, .js, etc) should be sent along with a specific .html, and sends them altogether in the initial response. But, if in your "original" .html you do not have this header.html file imported (because you intend to call it later with a script), it won't be sent initially. So, when your JavaScript/jQuery requests it (this will happen much later, when HTML and your JavaScript will get "interpreted"), your browser will send a second request to the server, wait for the answer, and then do its stuff... That's why this is slow. You can validate this, using any browser's developer tools, watching the header.html coming much later.
So, as a general advice (there are a lot of exceptions of course), import all your additional files in your original .html (or php) file if you care about speed. Use defer if needed. Do not import any files later using JavaScript.
I think, answers to this question are too old... currently some desktop and mobile browsers support HTML Templates for doing this.
I've built a little example:
Tested OK in Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 and Adblocker Browser 54.0
Tested KO in Safari 10.1, Firefox 56.0, Edge 38.14 and IE 11
More compatibility info in canisue.com
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
Your can get more examples in this HTML5 Rocks post
Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.
I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)
So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.
I hope this helps!
It is also possible to load scripts and links into the header.
I'll be adding it one of the examples above...
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
For a quick setup with plain javascript and because not answered yet, you could also use a .js file to store your redundant pieces (templates) of HTML inside a variable and insert it through innerHTML.
backticks are here the make it easy part this answer is about.
(you will also want to follow the link on that backticks SO Q/A if you read & test that answer).
example for a navbar that remains the same on each page :
<nav role="navigation">
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
</nav>
You can keep inside your HTMl :
<nav role="navigation"></nav>
and set inside nav.js file the content of <nav> as a variable in between backticks:
const nav= `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
` ;
Now you have a small file from which you can retrieve a variable containing HTML. It looks very similar to include.php and can easily be updated without messing it up (what's inside the backticks).
You can now link that file like any other javascript file and innerHTML the var nav inside <nav role="navigation"></nav> via
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
If you add or remove pages, you only have to update once nav.js
basic HTML page can be :
// code standing inside nav.js for easy edit
const nav = `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
`;
nav[role="navigation"] {
display: flex;
justify-content: space-around;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<!-- update title if not home page -->
<meta name="description" content=" HTML5 ">
<meta name="author" content="MasterOfMyComputer">
<script src="nav.js"></script>
<!-- load an html template through a variable -->
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<nav role="navigation">
<!-- it will be loaded here -->
</nav>
<h1>Home</h1>
<!-- update h1 if not home page -->
<script>
// this part can also be part of nav.js
window.addEventListener('DOMContentLoaded', () => {
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
});
</script>
</body>
</html>
This quick example works & can be copy/paste then edited to change variable names and variable HTML content.
another approach made available since this question was first asked is to use reactrb-express (see http://reactrb.org) This will let you script in ruby on the client side, replacing your html code with react components written in ruby.
Use ajax
main.js
fetch("./includes/header.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./includes/footer.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Liks</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header></header>
<main></main>
<footer></footer>
<script src="/js/main.js"></script>
</body>
</html>
You can use object tag of HTML with out use of JavaScript.
<object data="header.html" type="text/html" height="auto"></object>
Credits : W3 Schools How to Include HTML
Save the HTML you want to include in an .html file:
Content.html
Google Maps<br>
Animated Buttons<br>
Modal Boxes<br>
Animations<br>
Progress Bars<br>
Hover Dropdowns<br>
Click Dropdowns<br>
Responsive Tables<br>
Include the HTML
Including HTML is done by using a w3-include-html attribute:
Example
<div w3-include-html="content.html"></div>
Add the JavaScript
HTML includes are done by JavaScript.
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
Call includeHTML() at the bottom of the page:
Example
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>

Is there a way to link html sections to an html file? [duplicate]

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>

Keeping modal only at one place (Bootstrap)

I am building a website using bootstrap and i have to use the same modal on every page. Right now i have to copy the whole code into every html and then it becomes available to every page but this is isn't the ideal way of doing things so i would like if anyone suggests me a way that i don't have to copy the same html code to every file. I want a way that the same html code becomes available to all pages while it is kept only at one place.
I cannot post my code here but i'll try to tell you my problem exactly.
<!-- navbar for website -->
1 html code
<!-- sign in and login modal(buttons are on navbar) -->
2 html code
<!-- main body -->
3 html code
4 html code
5 html code
<!-- footer for website -->
6 html code
7 html code
For example according to above block navbar, modal and footer(1,2,6,7 lines) remain same for every page. How can I put all that elsewhere and just link it somehow like css files are linked(something like that). I can give you more information just ask in comments(other than my exact code).
There are two ways to accomplish your goal:
Using Javascript
<script>
function includeModal() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
Then call it
<script>
includeModal();
</script>
Using HTML
<div w3-include-html="modal.html"></div>
At first you need to divide your html, like make another file for only Footer i.e. Footer.html, and header.html etc.
Then use JQuery to include them.
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("header.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
The jQuery .load() documentation is here

Bulk editing HTML on multiple pages?

For example, if I'm building a page header with a menu that will appear on every single page of a website, if and when I want to make changes to the menu on every page, is there a way to implement this change on every page without having to edit every single HTML page?
Let's say my menu has 5 tabs and at a later date I want to add a 6th tab, or remove a tab, is there an efficient way of doing this without having to manually edit the HTML on every single page?
HTML itself doesn't provide such a mechanism, though SGML, the language in which the HTML element vocabulary is/was originally specified, does in the form of entities/entity references. Using SGML entities, you'd typically create an SGML file containing just your menu, and then pull-in that file from multiple individual page content files:
<!-- content of menu.sgml file -->
<nav>
<ul>
<li>About</li>
<li>Blog</li>
<!-- ... further menu items -->
</ul>
</nav>
<!-- content of page.sgml pulling-in menu.sgml -->
<!DOCTYPE html [
<!-- this declares the "menu" entity -->
<!ENTITY menu SYSTEM "menu.sgml">
]>
<html>
<head>
<title>Menu demo</title>
</head>
<body>
<!-- this pulls-in menu.sgml as if it were part
of page.sgml directly -->
&menu
<main>
<h2>Heading</h2>
<p>Main content of your page</p>
</main>
</body>
</html>
Now you'd only edit menu.sgml and have your updated menu content always up-to-date in any page files referencing menu.sgml. You can even leave out the declaration for menu (and the whole DOCTYPE document prolog) since SGML resolves the &menu entity reference to a file of that name in the same directory as the referencing file by default.
Note: browsers don't implement SGML. To make use of SGML in browsers (and/or on the server side as well when using node.js), you can use my sgmljs.net SGML parser/lib; see http://sgmljs.net/docs/sgmlrefman.html#general-entities for discussion of relevant entity techniques.
Commonly used server-side template libs such as Jade, pug, handlebars, mustache, etc. all have their own mechanisms called partials or includes to get functionality more or less equivalent to SGML general entities.
If your page is also using PHP you could add it with the help of the include statement there.
Otherwise here is a JavaScript solution:
menu.html
Start<br>
Page 2<br>
Page 3<br>
script.js
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
Your "normal" files
<div w3-include-html="menu.html"></div> <!-- put that line where you want to include the HTML. -->
<script>
includeHTML();
</script> <!-- Put that at the end of your file. -->
From here: https://www.w3schools.com/howto/howto_html_include.asp