router.js 2.1 KB

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