Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 433
Abu Avatar asked Oct 03 '13 02:10

Abu


People also ask

How do I call an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Is it possible to dynamically load external JavaScript files in JavaScript?

Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.

What is the ideal place to load the external JavaScript?

if you planned to insert external your JS script(s), then the best place is in head of the page. if you planed to use pages on smartphones, then bottom of page, just before tag.

Where is the external JavaScript file stored?

The file can be saved anywhere in the Web Project directory. It is common practice to put JavaScript files in a folder named "javascript" or "src" when building web and mobile applications.


1 Answers

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.

like image 62
tremor Avatar answered Sep 29 '22 20:09

tremor