ai didi

javascript - 从其他页面获取 HTML 并将脚本附加到 "type=' 模块后'“它只工作一次然后停止

转载 作者:行者123 更新时间:2023-12-05 04:46:13 24 4
gpt4 key购买 nike

我正在使用“fetch”动态加载具有自己脚本的 html 页面内容,它工作正常,但页面需要具有“script type='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);
});

最佳答案

一种解决方案是替换 <script>通过调用 dynamic import 创建标签:

      import(`./pages/${htmlPath}.js`).then((module) => {
module.onload();
});

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

这是一个 working CodeSandbox .

关于javascript - 从其他页面获取 HTML 并将脚本附加到 "type=' 模块后'“它只工作一次然后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68924771/

24 4 0
文章推荐: unity3d - 我无法统一将 Sprite 拖入动画窗口
文章推荐: javascript - 在上传到谷歌云存储之前用锐利调整图像大小
文章推荐: aws-amplify - 如何将 AWS secret 管理器与 Amplify 结合使用
文章推荐: flutter - 如何在 Flutter 中使用 GetX 监听 FocusNode
行者123
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com