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

51,214

Solution 1

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.

Solution 2

Your code almost works. 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 that'll do it.

EDIT:

Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.

Solution 3

Are you using jQuery? If so, you can try $.getScript().

You might also want to 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>

Solution 4

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

An info I missed was, that the path has to be absolute.

Share:
51,214

Related videos on Youtube

Abu
Author by

Abu

Updated on July 09, 2022

Comments

  • Abu
    Abu almost 2 years

    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.

    • Xymostech
      Xymostech over 10 years
      Are you sure your code is running? It looks like it should work to me, and it's working perfectly fine for me in Chrome.
  • Sha
    Sha about 5 years
    "text/javascript" is no longer needed on scripts and it is advised to remove type
  • rescuecreative
    rescuecreative about 5 years
    @Sha true. I only included it here because it's part of the original question.