Skip to content

Instantly share code, notes, and snippets.

@leonsilicon
Last active January 8, 2022 03:56
Show Gist options
  • Save leonsilicon/1278d429d7c915a9866bc6ea73453d9a to your computer and use it in GitHub Desktop.
Save leonsilicon/1278d429d7c915a9866bc6ea73453d9a to your computer and use it in GitHub Desktop.
Properly set up routing for an SPA hosted on GitHub pages
<!DOCTYPE html>
<html>
<head>
<script>
sessionStorage.redirect = location.href;
const projectPages = true; // If you're using the base .github.io domain without a path (i.e. <name>.github.io is your home page), set this to false
const l = window.location;
const repo = projectPages ? '/' + l.pathname.split('/')[1] : '';
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + repo
);
</script>
</head>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<script>
// Redirects user from 404
(function () {
var redirect = sessionStorage.redirect;
delete sessionStorage.redirect;
if (redirect && redirect != location.href) {
history.replaceState(null, null, redirect);
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment