GitHub Pages 如何实现 SPA

前因

这两天在 GitHub Pages 里面托管了一个小 DEMO,可是 DEMO 是 SPA 的,然而 GitHub Pages 是没法支持 SPA 配置的,这里记录一下解决方案。javascript

404

GitHub Pages 虽然不支持 SPA,可是支持自定义 404 页面。参考:GitHub Pages 404html

You can display a custom 404 error page when people try to access nonexistent pages on your site.vue

经过建立一个 404.html(或者 404.md,不过须要作一些配置,具体可查看上方连接),访问不存在的页面都会跳转到 404 的页面。java

初次方案

既然可使用 404 页面捕获不存在的页面请求,那么就能够 借助 404 页面进行跳转git

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>404</title>
        <script> // 或者特定的路径 location.href = location.origin; </script>
    </head>
    <body></body>
</html>
复制代码

借助 404 页面,可让全部页面跳转到 index 中,算是简单的实现了 SPA。github

进阶方案

虽然实现了 404 到 index 的跳转,可是离真正的 SPA 体验仍是差了,每次进入页面只能跳转到首页。api

差的就是 跳到 index 可是路由信息却丢失了,这时候能够想到想办法保存下跳转前的路由信息,而后跳转后还原就能够了。大概步骤以下:浏览器

  1. 在 404 页面,将当前的路由信息记录下来
  2. 携带路由信息跳转到 index
  3. 进入 index 后检查路由信息,进行还原

404.html网站

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>404</title>
        <script> location.href = location.origin + '/?page=' + encodeURIComponent(location.href.replace(location.origin, '')); </script>
    </head>
    <body></body>
</html>
复制代码

index.htmlui

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>index</title>
        <script> (function() { if (location.search) { var params = {}; location.search .replace(/^\?/, '') .split('&') .forEach(s => { var v = s.split('='); params[v[0]] = v[1]; }); if (params.page) { history.replaceState(null, null, decodeURIComponent(params.page)); } } })(); </script>
    </head>
    <body><script type="text/javascript" src="main.min.js"></script></body>
</html>
复制代码

经过上述步骤能够将路由信息完整的带到 index 中还原,从而实现 SPA 的效果,固然,会看到浏览器地址栏中路由的跳转,体验上稍微差了点,不过功能上已经基本无异。

最终效果

能够看下效果:

github-spa.gif

网站地址:rapiop.github.io/vue/

GitHub 地址:github.com/rapiop/rapi…

注意事项

  • 大部分 GitHub Pages 有本身的项目路径,如 test.github.io/test/,这时候须要对上述逻辑作一些处理,不能直接套用。
  • URL 参数中的 page 能够自定义,注意不要和已有路由信息冲突。
  • 除了 URL 传参,也能够经过 localStorage 之类的手段传递路由,不过极小几率会有问题,好比 404 页面还没跳转时关闭了页面,下一次到首页打开可能会跳到以前存储的路由中去之类的。

参考

相关文章
相关标签/搜索