简体   繁体   中英

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). But the behavior is synchronous and the page gets blocked until the javascript gets loaded completely. I want to know is there any possible work around by which i can embed the javascript asynchronously without using xhr.

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 . But if you insert <script>code goes here</script> , the execution begins without delay (as soon as you relinquish the JS thread). 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. Another possibility is to use some excellent module systems that have come into existence recently, like RequireJS, that figure out all this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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