Created
July 19, 2018 00:54
-
-
Save chellimiller/5aba9da209dfe00104b220d18f20ce41 to your computer and use it in GitHub Desktop.
Super tiny router for a single page app
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
<!doctype html> | |
<html> | |
<title></title> | |
<meta charset="utf-8"> | |
<style> | |
page { | |
display: none; | |
} | |
</style> | |
<body onload="inform()"> | |
<header> | |
<button onclick="routerRedirect('test')">Test</button> | |
<a href="#/foo">End</a> | |
</header> | |
<main id="outlet"></main> | |
<page id="example">Example</page> | |
<page id="bar">Foobar</page> | |
</body> | |
<script> | |
function routerRedirect(url) { | |
window.location.hash = "/" + url; | |
} | |
function updateRouterOutlet(url) { | |
let page = document.getElementById(getRoute(url)); | |
document.getElementById("outlet").innerHTML = page.innerHTML; | |
} | |
window.onhashchange = () => { | |
updateRouterOutlet(location.hash) | |
}; | |
function getRoute(url) { | |
if (url.startsWith('#')) { | |
url = url.substring(1); | |
} | |
if (url.startsWith('/')) { | |
url = url.substring(1); | |
} | |
return routes[url]; | |
} | |
var routes = { | |
'test': 'example', | |
'foo': 'bar', | |
} | |
function inform() { | |
console.log('BODY RELOAD'); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment