feat(sidepanel): 重构路由系统并优化页面加载逻辑

- 移除冗余的开发预览页面 `index.html`
- 路由配置改为声明式结构,支持自动加载 HTML 和脚本
- 新增 `data-route` 属性用于导航按钮绑定路由路径
- 实现基于事件委托的路由跳转机制
- 重写 `Router.js` 核心逻辑,支持异步加载页面模块
- 改进 `domUtils.js` 中 `addClass` 和 `removeClass` 方法兼容性与健壮性
- 新增 `scriptLoader.js` 工具模块用于动态加载和清理页面脚本
- 时间戳页面初始化方式调整为 IIFE 并挂载至全局作用域
This commit is contained in:
雨霖铃
2025-11-30 23:34:40 +08:00
parent 884fc09750
commit 2761dbe13f
7 changed files with 225 additions and 333 deletions
+16 -37
View File
@@ -1,48 +1,21 @@
console.log('Before creating router');
import { Router } from '../modules/Router.js';
import * as PageModules from '../../dist/timestamp.js';
const config = {
routerViewId: 'app', // 路由切换的挂载点 id
stackPages: false, // 多级页面缓存
animationName: 'fade', // 切换页面时的动画
routerViewId: 'app',
stackPages: false,
routes: [
{
path: '/home',
name: 'home',
callback: async () => {
// 1. 加载 HTML
const html = await fetch('pages/timestamp.html').then((r) => r.text());
document.getElementById('home').innerHTML = html;
// 2. 动态加载对应 JS
const script = document.createElement('script');
script.src = '/dist/timestamp.js'; // IIFE 打包后的文件
script.onload = () => {
// 3. 执行 IIFE 暴露的全局对象方法
TimestampPage.init(); // 假设 timestamp.js 输出 name: 'TimestampPage'
};
document.body.appendChild(script);
},
name: 'timestamp',
html: 'pages/timestamp.html',
script: '../dist/timestamp.js',
},
{
path: '/todo',
name: 'todo',
callback: async () => {
// 1. 加载 HTML
const html = await fetch('pages/todolist.html').then((r) => r.text());
document.getElementById('todo').innerHTML = html;
// 2. 动态加载对应 JS
const script = document.createElement('script');
script.src = '/dist/timestamp.js'; // IIFE 打包后的文件
script.onload = () => {
// 3. 执行 IIFE 暴露的全局对象方法
TimestampPage.init(); // 假设 timestamp.js 输出 name: 'TimestampPage'
};
document.body.appendChild(script);
},
html: 'pages/todolist.html',
script: '',
},
],
};
@@ -52,7 +25,13 @@ console.log('Router created:', router);
router.init(config);
console.log('Router initialized');
document.getElementById('todo-jump').addEventListener('click', () => {
console.log('Jumping to todo page');
window.linkTo('#/todo');
document.addEventListener('click', (event) => {
const btn = event.target.closest('[data-route]');
if (!btn) return;
const path = btn.getAttribute('data-route');
if (!path) return;
// 触发 hash 路由跳转
window.location.hash = path;
});