javascript - 使用 xhr 加载脚本并运行它
问题描述
我正在尝试动态加载脚本,但它不起作用,我在这里做错了什么?
<script>
function loadXMLDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "haromd.js", true); xhttp.send(); };
loadXMLDoc();
</script>
<script type="module" id="demo"></script>
外部脚本文件仅包含进入模块类型脚本标签的脚本。当相同的脚本在没有 xhr 的脚本标签中时,它可以正常工作/运行。
解决方案
当您收到它的内容时,您将需要创建一个新的脚本元素。
修改现有脚本标签中的文本不会执行它,但是当新的脚本元素插入 DOM 时,它将执行
简单的例子
const get_code = (msg) => `console.log('${msg}')`;
// try inserting in existing script element
document.getElementById('existing').textContent = get_code('Existing script tag');
console.log('Nothing prior in console')
// create new script element
const scr = document.createElement('script')
scr.textContent = get_code('New script tag')
document.body.append(scr)
<script id="existing"></script>
推荐阅读
- mysql - 过滤mysql数据库中的数据
- javascript - 使用 Angular 在 HTML 上编写元素引用
- kotlin - IntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序
- machine-learning - 不同的成本函数利弊
- python - 如何使用 Jupyter 笔记本将 txt 文件插入 sklearn
- c# - .NET 4.7.x 中的 .NET 反射比 3.5 慢 3 倍
- javascript - 导航 json 对象图的建议
- javascript - TypeError:无法读取未定义的属性“发送”?
- c# - 2 个 Visual Studio 启动 2 个不同的 IIS Express 服务器
- ios - 为什么我可以播放我的 app bundle 中的视频,但不能播放下载到文件系统的视频?