我正在尝试使用 fetch API 加载 HTML 页面及其 JavaScript 脚本
我可以使用 ajax 和 JQuerySee here https://stackoverflow.com/questions/50847274/fetch-api-not-getting-full-html-page加载页面,但是可以使用 fetch API 吗?
这是代码演示:
我假设你在本地主机上运行这个
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>fetch API</title>
</head>
<body>
<p>index page</p>
<div id="content">
</div>
<script>
fetch('./page.html')
.then(data => data.text())
.then(html => document.getElementById('content').innerHTML = html);
</script>
</body>
</html>
要加载的页面:
<!-- page.html -->
<p> i am the loaded page</p>
<script type="text/javascript">
alert("Javascript is working");
</script>
The <p>
tag I am the loaded page
将会运行,但是<script>
wont alert
或任何类型的 JavaScript
我发现使用 eval() 的其他答案在这里很有帮助,但遇到了一个问题,因为我的动态加载内容正在导入一个外部脚本,在 Firefox 中给出 CORS 警告,例如:
<script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection"></script>
因此,我对其进行了一些调整,以在不使用 eval() 的情况下注入脚本标签,以允许来自其他域的外部脚本以及嵌入式脚本。然后,我修改为按照定义的顺序加载脚本,等待加载完成后再加载下一个 - 这是因为我的页面上的嵌入式脚本依赖于正在加载的外部脚本的功能。
fetch("/mypage.html").then(response => {
return response.text();
}).then(data => {
const app = document.getElementById("app");
app.innerHTML = data;
// Load scripts in the order they are defined
// Note that inserting scripts into an element using innerHTML doesnt work - hence this logic
var scripts = app.querySelectorAll("script");
if (scripts !== null && scripts.length > 0) {
var loadScript = index => {
if (index < scripts.length) {
var newScript = document.createElement("script");
if (scripts[index].innerText) {
var inlineScript = document.createTextNode(scripts[index].innerText);
newScript.appendChild(inlineScript);
}
else {
newScript.src = scripts[index].src;
}
scripts[index].parentNode.removeChild(scripts[index]);
newScript.addEventListener("load", event => loadScript(index + 1));
newScript.addEventListener("error", event => loadScript(index + 1));
app.appendChild(newScript);
}
}
loadScript(0); // Start loading script 0. Function is recursive to load the next script after the current one has finished downloading.
}
}).catch(err => {
console.warn('Something went wrong.', err);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)