Skip to content

Instantly share code, notes, and snippets.

@rosvik
Last active February 10, 2019 22:05
Show Gist options
  • Select an option

  • Save rosvik/453291436db993a43c605a27eed3110e to your computer and use it in GitHub Desktop.

Select an option

Save rosvik/453291436db993a43c605a27eed3110e to your computer and use it in GitHub Desktop.
JS/AJAX load file to HTML element
var params = {
htmlid: 'content',
path: 'pages/en/',
extention: '.html'
}
// Check for parameters at page load
getParam();
function getParam() {
var url_string = document.location.href;
var url = new URL(url_string);
var param = url.hash.substr(1);
if (param != "") {
loadHtml(param);
} else {
loadHtml('home');
}
}
// Get content of file
function loadHtml(file, htmlId = params.htmlid) {
var xhr= new XMLHttpRequest();
xhr.open('GET', params.path + file + params.extention, true);
xhr.onreadystatechange= function() {
if (this.readyState !== 4) return;
if (this.status !== 200) { // Error handling
document.getElementById(htmlId).innerHTML = "<h1>" + this.status + "</h1>";
return;
}
document.getElementById(htmlId).innerHTML = this.responseText;
window.history.pushState('page', 'Title', '#' + file);
// Update EventListener for new urls
listenUrls();
}
xhr.send();
}
// Make internal links fire the loadHtml function
listenUrls();
function listenUrls() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function(event) {
try { // External url
new URL(this.getAttribute('href'));
} catch(err) { // Not a valid url
var url = this.getAttribute('href');
event.preventDefault();
loadHtml(url);
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment