I want home.html to load in When using Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server You can use the jQuery : this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as There is this plugin on github that load content into an element. Here is the repo https://github.com/abdi0987/ViaJS If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash For ex : This approach makes use of modern Javascript features like The See the fetch API documentation for more details.
$("#content").load("content.html");
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
argHtml
<iframe src="home.html" width="100" height="100"/>
Fetching HTML the modern Javascript way
async/await
and the fetch
API. It downloads HTML as text and then feeds it to the innerHTML
of your container element./**
* @param {String} url - address for the HTML to fetch
* @return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
await (await fetch(url)).text()
may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}