router.js 2.4 KB

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