router.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const routes = {
  2. page1: "pages/page1.html",
  3. page2: "pages/page2.html",
  4. page3: "pages/page3.html",
  5. page4: "pages/page4.html",
  6. page5: "pages/page5.html",
  7. page6: "pages/page6.html",
  8. page7: "pages/page7.html",
  9. page8: "pages/page8.html",
  10. };
  11. let currentPage = null;
  12. const pageHandlers = {
  13. page1: {},
  14. page2: {
  15. init: () => window.initPage2?.(),
  16. exit: () => window.exitPage2?.()
  17. },
  18. page3: {},
  19. page4: {},
  20. page5: {},
  21. page6: {},
  22. page7: {},
  23. page8: {
  24. init: () => window.initPage8?.(),
  25. exit: () => window.exitPage8?.()
  26. },
  27. };
  28. function clearOldScripts() {
  29. document.querySelectorAll("script[data-dynamic='1']").forEach(s => s.remove());
  30. }
  31. function runScripts(container) {
  32. const scripts = container.querySelectorAll("script");
  33. scripts.forEach(oldScript => {
  34. const s = document.createElement("script");
  35. s.dataset.dynamic = "1";
  36. if (oldScript.src) {
  37. s.src = oldScript.src;
  38. } else {
  39. s.textContent = oldScript.textContent;
  40. }
  41. document.body.appendChild(s);
  42. });
  43. }
  44. async function loadPage(name) {
  45. const view = document.getElementById("view");
  46. const url = routes[name];
  47. if (!url) {
  48. view.innerHTML = "<div class='card'>无法找到页面</div>";
  49. return;
  50. }
  51. try {
  52. const res = await fetch(url, { credentials: "include" });
  53. const html = await res.text();
  54. if (html.includes("login.html") || html.includes("登录")) {
  55. window.location.href = "/";
  56. return;
  57. }
  58. const temp = document.createElement("div");
  59. temp.innerHTML = html;
  60. if (currentPage && pageHandlers[currentPage]?.exit) {
  61. pageHandlers[currentPage].exit();
  62. }
  63. clearOldScripts();
  64. view.innerHTML = "";
  65. view.appendChild(temp);
  66. runScripts(temp);
  67. currentPage = name;
  68. if (pageHandlers[name]?.init) {
  69. pageHandlers[name].init();
  70. }
  71. } catch (e) {
  72. console.error("loadPage error:", e);
  73. view.innerHTML = "<div class='card'>页面加载失败</div>";
  74. }
  75. }