[英]How can I tell a dynamically inserted <script> tag to… run
I'm dynamically inserting a <script>
tag with a src
attribute and no content. 我正在动态插入具有src
属性且没有内容的<script>
标记。 But the browser does not pull down that src and run the script after the insertion -- the tag just sits there in the DOM. 但是浏览器不会在插入后拉下该src并运行脚本-标记仅位于DOM中。
Is it possible for me to tell the browser to "run" the script tag? 我可以告诉浏览器“运行”脚本标签吗?
Because of the other code I'm working with, it's easier for me to keep the code fetched via the src
attribute than to fetch it myself and insert it into the body of the tag -- but if that's necessary, I can do that too (and welcome any advice on that). 由于我正在使用其他代码,因此相对于自己自己将其插入并将其插入标签的主体,保持通过src
属性获取的代码要容易得多,但是如果有必要,我也可以这样做(并欢迎提供任何建议)。
update with requested info 用请求的信息更新
document.getElementById("my-div").innerHTML = "the script tag, which stack overflow wants to strip";
我插入了这样的标签(jQuery的html函数剥离了脚本标签): document.getElementById("my-div").innerHTML = "the script tag, which stack overflow wants to strip";
Try following code:: Its working 尝试以下代码::其工作
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src =MY_URL;
$("#YOUR_ELEMNT_ID").append( script );
it should run right after the browser inserts the script into the dom, but you can try to wrap your script into a function and call that function after the script loads : 它应该在浏览器将脚本插入dom后立即运行,但是您可以尝试将脚本包装到一个函数中,并在脚本加载后调用该函数:
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src',script_url);
script.onreadystatechange= function () {
if (this.readyState == 'complete')
initScript();//the whole script is wrapped in this function
}
script.onload= initScript;
Hope this helps! 希望这可以帮助!
You could have a setTimeout in the main script to check if the new script is there.. and if it is, then run it. 您可能在主脚本中有一个setTimeout,以检查新脚本是否存在..如果存在,请运行它。 Do you know if it downloads the file or if it just does nothing? 您知道它是否下载文件还是什么都不做? Check with Chrome's Network monitor. 检查Chrome的网络监视器。
I think there's a dynamic way to load Javascript without the src= tag, as well, but I haven't personally done it. 我认为也有一种动态方式来加载没有src =标记的Javascript,但我个人还没有做到这一点。
Why not have all the javascript pre-loaded and just put through some inline JS to execute it? 为什么不将所有JavaScript预加载并仅通过一些内联JS来执行呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.