用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的脚本标记中包含相同的脚本,则该脚本可以正常运行/运行,没有任何问题。

zz7630 回答:用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>

本文链接:https://www.f2er.com/1335556.html

大家都在问