Javascript – How to load an external Javascript file during an “onclick” event

dojohtmljavascriptjqueryjsp

I have 2 divs in my HTML.

<div id="div1"></div>
<div id="div2"></div>

On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".

I tried including the JS file on onclick event like below,

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js"; 
document.getElementsByTagName("head")[0].appendChild(script);

This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).

Is there any other way that I could proceed?

Thanks in Advance.

Best Answer

Using jQuery's $.getScript() function should do the job for you.

Here is a slice of sample code:

$("button").click(function(){
  $.getScript("demo_ajax_script.js");
}); 

If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.