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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With