When I click...">

How to load external Javascript file during onclick event?

I have 2 divs in my HTML.

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

When I click "div2" I want to load an external javascript file, for example, " https://abcapis.com/sample.js ".

I tried to include the JS file in the onclick event, as shown 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 header section, but it didn’t load, as the script tag will only be loaded on page load (correct me here if I am wrong).

Is there any other way that I could continue.

Thanks at Advance.

+8
javascript jquery html jsp dojo
source share
4 answers

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

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

Here is a sample code snippet:

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

If you are not using jQuery, you need to learn how to use AJAX to dynamically load a new script into your page.

+15
source share

Your code is almost working. You need to use .setAttribute . Here is my working code. I used jQuery as my script:

 var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', 'jquery.min.js'); document.head.appendChild(script); 

And it will be done.

EDIT:

Additional Information. When you do something like script.type = 'text/javascript' , you set the property of the object, but it is not necessarily the same as associating this property with the actual node attribute.

+6
source share

Do you use jQuery? If so, you can try $. GetScript () .

You can also check this answer . But basically you can do something like this:

 <a href='linkhref.html' id='mylink'>click me</a> <script type="text/javascript"> var myLink = document.getElementById('mylink'); myLink.onclick = function(){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = "Public/Scripts/filename.js."; document.getElementsByTagName("head")[0].appendChild(script); return false; } </script> 
+2
source share
 $("button").click(function(){ $.getScript("demo_ajax_script.js"); }); 

The information I missed was that the path should be absolute.

+1
source share

All Articles