我有一点小问题,当我试图加载与JS或JQ脚本。我已经加入了体的底部,之后另一个脚本的jQuery的。从这个剧本我加载一个多个脚本,但有时我需要刷新页面,使其工作。
我曾尝试与JS:
$(window).on("load", function() {
var script = document.createElement("script");
script.src = "scriptPath.js";
script.async = false; // the result is same with true
script.onload = function () {
//do something here
};
document.body.appendChild(script);
});
我曾尝试与JQ:
$(window).on("load", function() {
$.getScript( "scriptPath.js" )
.done(function() {
//do something here
})
.fail(function() {
//do something here
});
});
我也试过头标记加载脚本,但结果是一样的。任何建议什么可以这样做的原因?
这里是一个工作的片断..
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>title</title>
</head>
<body>
<div>
BOO
</div>
<script>
(function () {
var script = document.createElement("script");
script.src = "2.js";
script.async = false; // the result is same with true
script.onload = function () {
console.log(booVar);
};
document.body.appendChild(script);
})();
</script>
</body>
</html>
2.js内容:
var booVar = 'booV';
请注意,部分是在身体在这种情况下结束。如果相同的脚本被放置在的一部分,它不会工作,因为document.body的是在这一点空。