js 实现spa
实现 SPA(单页应用)的核心思路
在 JavaScript 中实现 SPA 的关键在于动态加载内容并更新 DOM,避免页面刷新。以下是几种常见方法:
基于 History API 的路由
利用 history.pushState 和 popstate 事件实现无刷新路由跳转:
// 路由表
const routes = {
'/': '<h1>Home Page</h1>',
'/about': '<h1>About Page</h1>'
};
// 渲染函数
function render(path) {
document.getElementById('app').innerHTML = routes[path] || '<h1>404</h1>';
}
// 初始化路由
window.addEventListener('popstate', () => render(window.location.pathname));
// 导航拦截
document.addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
e.preventDefault();
history.pushState({}, '', e.target.href);
render(window.location.pathname);
}
});
// 首次加载
render(window.location.pathname);
基于 Hash 的路由
使用 URL hash 实现简单路由:
window.addEventListener('hashchange', () => {
const path = window.location.hash.slice(1) || '/';
document.getElementById('app').innerHTML =
`<h1>${path === '/' ? 'Home' : path} Page</h1>`;
});
动态组件加载
通过动态导入实现按需加载:
const components = {
home: () => import('./Home.js'),
about: () => import('./About.js')
};
async function loadComponent(name) {
const module = await components[name]();
document.getElementById('app').appendChild(module.default());
}
使用现代框架
推荐使用现成的 SPA 框架:
- React + React Router
- Vue + Vue Router
- Angular 内置路由
以 Vue 为例:
// Vue Router 示例
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = VueRouter.createRouter({
history: VueRouter.createWebHistory(),
routes
});
const app = Vue.createApp({});
app.use(router);
app.mount('#app');
关键注意事项
- SEO 优化:SPA 需要服务端渲染(SSR)或静态生成(SSG)解决 SEO 问题
- 状态管理:复杂应用需引入状态管理库(如 Vuex/Pinia、Redux)
- 代码分割:通过动态导入实现性能优化
- 404 处理:需配置兜底路由
完整示例结构
典型 SPA 项目结构:
public/
index.html
src/
components/
pages/
router.js
app.js
HTML 基础模板:

<!DOCTYPE html>
<html>
<head>
<title>SPA Example</title>
</head>
<body>
<div id="app"></div>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<script src="app.js"></script>
</body>
</html>






