Reputation: 407
I have been searching a way to include html files into another html file...for example i have 3 html files... 1) header.html 2) content.html 3) footer.html... and i would like to include the header.html and the footer.html inside the content.html so i could create a multiple websites, include the header and footer, and if i have to change something to header and footer to be affected to all websites. I have read about imports in html file which i include my file like this
<link rel="import" href="header.html">
I have tried it and its not working. Is the import supported by the browsers? If yes how would you make it work?
I am looking for a similar way like php include, but for html.
Thanks.
Upvotes: 1
Views: 1806
Reputation: 133
Well my answer is other more easy way. I used JQuery and files of html5 and one standalone script.
This is the structure on files:
My index.html has containers for load the templates to Header and Footer.
The Html5 of templates, for example is:
The result:
Upvotes: 1
Reputation: 853
The correct to do this is through server side pages includes or through JavaScript.
PHP example:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
Javascript Example:
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "header.html", true);
xmlhttp.send();
}
</script>
Javascript with JQuery Library:
$.ajax({
url: "header.html",
success: function(data){
$("myDiv").html(data.responseText);
}
});
If you don't want to get your hands dirty in js you can do the following using a script provided by w3schools:
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="header.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Upvotes: 3
Reputation: 1109
That's impossible. You can't include an HTML page into another, or you need to use PHP include()/require() function.
Else, you can load dynamically any page with AJAX and append the output to your main page, like this (here I use jQuery) :
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'page.html',
success: function(content) {
document.body.innerHTML += content;
}
});
</script>
</body>
(Note that you should add an 'error' event etc. etc. it's just an easy exemple)
Upvotes: 1