繁体   English   中英

使用 xhr 加载脚本并运行它

[英]loading a script with xhr and run it

我正在尝试动态加载脚本,但它不起作用,我在这里做错了什么?

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM