Leo T Abraham
Leo T Abraham

Reputation: 2437

How to include a js file, on satistying the condition in jquery

<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>

Upvotes: 1

Views: 1584

Answers (3)

Felix
Felix

Reputation: 38102

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");

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

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);

Upvotes: 3

Eugen Timm
Eugen Timm

Reputation: 744

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);

Upvotes: 2

Related Questions