How to load an external Javascript file during an "onclick" event?

Abu picture Abu · Oct 3, 2013 · Viewed 44.4k times · Source

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.

Answer

tremor picture tremor · Oct 3, 2013

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

http://api.jquery.com/jQuery.getScript/

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.