从其他页面获取 HTML 并在脚本中附加 "type='module'" 后,它只工作一次然后停止

After fetch HTML from other page and append the script with "type='module'" it works just one time and then stops

我正在使用“fetch”动态加载具有自己脚本的 html 页面内容,它工作正常,但页面需要具有“脚本类型='module'”,因为他们从其他页面导入功能。 问题是当 type='module' 被设置时,它只加载一次脚本,然后它停止工作。

这里是codesandbox

中的完整代码

无论如何这是我的结构文件夹

index.html
main.js

functions
 ┗ someFunc.js

pages
 ┣ home.html
 ┣ home.js
 ┣ page_1.html
 ┣ page_1.js
 ┣ page_2.html
 ┗ page_2.js

在 main.js 中,我有这样的获取函数:

//Event click of the main menu
let nav = document.querySelector("#main_nav");
nav.querySelectorAll("a").forEach((aElement) => {
  aElement.addEventListener("click", (e) => {
    //Each element "a" have the attribute "data-path='name_of_file'"
    loadHTML(e.target.dataset.path);
  });
});

//Funciton that loads the content from other pages using "fetch"
function loadHTML(htmlPath) {
  fetch(`pages/${htmlPath}.html`)
    .then((res) => res.text())
    .then((html) => {
      let page_content = document.querySelector("#page_content");
      page_content.innerHTML = html;
      let script = document.createElement("script");
      script.src = `pages/${htmlPath}.js`;
      //set the type='module' in the script when the page is "page_1"
      if (htmlPath === "page_1") {
        script.type = "module";
      }
      page_content.appendChild(script);
    });
}

这是我的主菜单:

    <nav id="main_nav">
      <li><a href="#" data-path="home">Home</a></li>
      <li></li>
      <li><a href="#" data-path="page_1">Page 1</a></li>
      <li></li>
      <li><a href="#" data-path="page_2">Page 2</a></li>
      <li></li>
    </nav>

感谢所有抽出时间的人。

更新... 我尝试使用动态导入,但它也不起作用 codesandbox

import("../functions/someFunc.js")
  .then((someFunc) => {
    someFunc.displayConsoleMSG("test");
  })
  .catch((err) => {
    console.log(err);
  });

一个解决方案是通过调用 dynamic import:

来替换 <script> 标记创建
      import(`./pages/${htmlPath}.js`).then((module) => {
        module.onload();
      });

为此,您需要在 .js 文件(上面,我将其命名为 onload)中定义一个函数,您在页面切换时调用该函数,而不是依赖关于代码加载过程的副作用。

这里是 working CodeSandbox