router.js 2.2 KB

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