router.js 1.9 KB

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