javascript - 仅在刷新后使用 JS 或 JQ 动态加载的脚本
问题描述
当我尝试使用 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
});
});
我也尝试在 head 标签中加载脚本,但结果是一样的。任何建议可能是什么原因?
解决方案
这是有效的片段..
<!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';
请注意,在这种情况下,section 位于正文的末尾。如果将相同的脚本放在 ' 部分中,它将无法工作,因为此时 document.body 将为空。
推荐阅读
- javascript - 在移动设备上将班级转移到另一个班级
- android - React-native run-android --variant=release 错误(RN 57.5)
- python - 如何在结果中跳过 ORM 开销?
- node.js - DiscordJS 和 Linux 的屏幕
- mysql - Laravel 一对多(多态)关系
- r - 获取最大 col 值并使其成为新变量
- google-apps-script - Google Apps 脚本中的 Google Docs API 作为外部 API(不作为扩展服务)
- java - Firebase 数据库不向 ListView 显示数据但写入 Firebase
- ffmpeg - 第一个TS文件最大:ffmpeg mp4 to hls
- typescript - 我们可以检查属性是否是只读的