1
<script>
     jQuery(document).ready(function(){
         jQuery(".tabmenu li").click(function(){
             var current_tab = jQuery(this).attr("class");
             var res = current_tab.replace(" active_tab",""); 
             if(res == 'tabmenu-8')
             {

             }

         });

     });
</script>

I have a script, which is written above. What I want is, I want to include a js file on satisfying the if condition. How can I do that? I tried different methods I found while searching in google, but nothing helped me.

This is the script I want to add there

<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
Leo T Abraham
  • 2,407
  • 4
  • 28
  • 54
  • 1
    The ` – Felix Apr 15 '14 at 09:11
  • @Felix I have got other library files to run this code. – Leo T Abraham Apr 15 '14 at 09:11
  • 1
    @LeoTAbraham His point is that the reason you can use `jQuery(foo)` is because you **already use** jQuery - loading it again will only result in problems. – h2ooooooo Apr 15 '14 at 09:13
  • I think this question solves your problem http://stackoverflow.com/questions/8085111/how-to-include-a-remote-javascript-file-conditionally – Asil Balaban Apr 15 '14 at 09:14

3 Answers3

3

try this in if condition:

var myscript = document.createElement('script');
myscript.setAttribute('src','http://code.jquery.com/jquery-1.9.1.js');
document.head.appendChild(myscript);
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • This contains a minor error: "my_awesome_script" (Line 2) is not defined since you named the variable just "myscript" – Eugen Timm Apr 15 '14 at 09:21
2

Adding additional scripts from JavaScript is actually quite easy. Your create a script-element and set the type and src attributes and just add it to the head (or body, it doesn't really matter)

var newScript = document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.setAttribute("src","http://code.jquery.com/jquery-1.9.1.js");
document.head.appendChild(newScript);
Eugen Timm
  • 744
  • 6
  • 13
1

You can use .append():

$('head').append($('<script>').attr('type', 'text/javascript').attr('src', '//code.jquery.com/jquery-1.9.1.js'));

If you've included jQuery, it's better to use $.getScript():

$.getScript("http://code.jquery.com/jquery-1.9.1.js");
Felix
  • 37,892
  • 8
  • 43
  • 55