router.js 2.0 KB

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