gpt4 book ai didi

javascript - JS在索引html和 block 中动态加载脚本

转载 作者:行者123 更新时间:2023-11-28 10:42:52 24 4
gpt4 key购买 nike

我想加载一个脚本,该脚本根据条件加载另一个脚本,并且该脚本正在向全局窗口添加一个变量。

<head>
<script src="load-something.js"></script>
<script>conosle.log(window.someVariable)</script>
</head>

加载某事.js

function loadScript( path ) {
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
script.src = path;
head.append(script);
}

if(condition) {
loadScript('pathToJsFile.js');
}

pathToJsFile.js

window.someVariable = ...

我的问题是 someVariable 未定义。是否可以强制脚本阻塞?

最佳答案

这个怎么样?

<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<script>
var condition = true;
var data;
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = this.responseText;
alert(data);
}
};
xhttp.open("GET", "test.json", true);
xhttp.send();
}
if (condition) {
loadDoc();
}
</script>
</head>
<body>
</body>
</html>

关于javascript - JS在索引html和 block 中动态加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49293972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com