简体   繁体   English

如何使用纯js将脚本标签插入并执行到DOM

[英]How to insert and execute script tag to the DOM using plain js

How to insert any string like <script>console.log('it works');</script> into browser DOM and see "it works" in browser console then? 如何在浏览器DOM中插入<script>console.log('it works');</script>类的字符串,然后在浏览器控制台中看到“ it works”?

jQuery's append function doing the thing: $('html').append('<script>console.log('it works'); but I am looking for light solution, ideally plain js jQuery的执行该操作的append函数: $('html').append('<script>console.log('it works');但我正在寻找简便的解决方案,最好是纯js

context: the string can be complex like <div><h1>Title</h1></div><div><script>console.log('it works');</script></div> - it should renders correct in the DOM and do all the JS staff context:字符串可以很复杂,例如<div><h1>Title</h1></div><div><script>console.log('it works');</script></div> -应该在DOM中呈现正确并执行所有JS工作人员

You can use insertAdjacentHTML to insert the HTML, then go back and look for the scripts and copy the script src or text, and insert the copy into the DOM to run it: 您可以使用insertAdjacentHTML插入HTML,然后返回以查找脚本并复制脚本src或文本,然后将副本插入DOM中以运行它:

 // Sticking with broadly-supported features: var htmlString = "<div><h1>Title</h1></div><div><script>console.log('it works');<\\/script></div>"; var target = document.getElementById("target"); target.insertAdjacentHTML("beforeend", htmlString); var scripts = target.getElementsByTagName("script"); while (scripts.length) { var script = scripts[0]; script.parentNode.removeChild(script); var newScript = document.createElement("script"); if (script.src) { newScript.src = script.src; } else if (script.textContent) { newScript.textContent = script.textContent; } else if (script.innerText) { newScript.innerText = script.innerText; } document.body.appendChild(newScript); } 
 <div id="target"></div> 

Note: Any inline document.write statements will not work as they would in the initial parse of a page; 注意:任何内联document.write语句都不会像在页面的初始解析中那样起作用。 instead, they'll re-open the document and replace all of its content with whatever they write. 取而代之的是,他们将重新打开该文档,并将其所有内容替换为所写内容。

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

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