简体   繁体   English

如何在按钮单击异步上附加javascript

[英]How to append javascript on button click async

In order to append script dynamically we need to create the script element and add the src property of the script element and finally append the script element in the head tag (or any other tag). 为了动态追加脚本,我们需要创建script元素并添加script元素的src属性,最后将script元素追加到head标记(或任何其他标记)中。 But the behavior is synchronous and the page gets blocked until the javascript gets loaded completely. 但是行为是同步的,页面被阻塞,直到javascript完全加载为止。 I want to know is there any possible work around by which i can embed the javascript asynchronously without using xhr. 我想知道是否有任何可能的解决方法,可以在不使用xhr的情况下异步嵌入javascript。

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'urlofthescript';
$("#someElement").append( script );
//the above line blocks the UI until it gets loaded. Why?

The <script src="..."> tag will always be synchronous, unless you use the async attribute . 除非您使用async属性 ,否则<script src="...">标记将始终是同步的。 But if you insert <script>code goes here</script> , the execution begins without delay (as soon as you relinquish the JS thread). 但是,如果您<script>code goes here</script>插入<script>code goes here</script> ,则执行将立即开始(无需放弃JS线程即可)。 So construct your code in a string or load it through AJAX, then document.createTextNode(code) , document.createElement('script') , appendChild code into script, then script onto document. 因此,将代码构造为字符串或通过AJAX加载,然后将document.createTextNode(code)document.createElement('script')appendChild代码加载到脚本中,然后将脚本加载到文档中。 Another possibility is to use some excellent module systems that have come into existence recently, like RequireJS, that figure out all this for you. 另一种可能性是使用最近出现的一些出色的模块系统,例如RequireJS,为您解决所有这些问题。

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

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