首页 > 解决方案 > 使用 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 的脚本标签中时,它可以正常工作/运行。

标签: javascriptxmlhttprequest

解决方案


当您收到它的内容时,您将需要创建一个新的脚本元素。

修改现有脚本标签中的文本不会执行它,但是当新的脚本元素插入 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>


推荐阅读