Created
May 3, 2020 00:35
-
-
Save asperduti/fa7d43af90351d1915982a6c02b30334 to your computer and use it in GitHub Desktop.
This is an example to show how simple it can be to implement a Single Page App(SPA) and how to use AJAX to make a request to the server and how to use the HTML5 History API to manipulate the browser’s history. This example is taken from "CS50’s Web Programming with Python and JavaScript"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script> | |
document.addEventListener('DOMContentLoaded', () => { | |
// Start by loading first page. | |
load_page('first'); | |
// Set links up to load new pages. | |
document.querySelectorAll('.nav-link').forEach(link => { | |
link.onclick = () => { | |
load_page(link.dataset.page); | |
return false; | |
}; | |
}); | |
}); | |
// Renders contents of new page in main view. | |
function load_page(name) { | |
const request = new XMLHttpRequest(); | |
request.open('GET', `/${name}`); | |
request.onload = () => { | |
const response = request.responseText; | |
document.querySelector('#body').innerHTML = response; | |
// Push state to URL. | |
document.title = name; | |
history.pushState({ 'title': name, 'text': response }, name, name); | |
}; | |
request.send(); | |
} | |
// Update text on popping state. | |
window.onpopstate = e => { | |
const data = e.state; | |
document.title = data.title; | |
document.querySelector('#body').innerHTML = data.text; | |
}; | |
</script> | |
</head> | |
<body> | |
<ul id="nav"> | |
<li><a href="" class="nav-link" data-page="first">First Page</a></li> | |
<li><a href="" class="nav-link" data-page="second">Second Page</a></li> | |
<li><a href="" class="nav-link" data-page="third">Third Page</a></li> | |
</ul> | |
<hr> | |
<div id="body"> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment