Skip to content

Instantly share code, notes, and snippets.

@asperduti
Created May 3, 2020 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asperduti/fa7d43af90351d1915982a6c02b30334 to your computer and use it in GitHub Desktop.
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"
<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