router.js 2.2 KB

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