9

I need to call one of two JavaScripts depending on a condition, like so:

<script type="text/javascript">
if(b_condition)
  <script type="text/javascript" src="http://script1.js"></script>
else
  <script type="text/javascript" src="http://script2.js"></script>
</script>

But this doesnt work. Any ideas how to call another JavaScript call in an If/Else block?

Shafique
  • 1,756
  • 6
  • 24
  • 35

10 Answers10

16

What the hell? Why on earth is everyone here advocating document.write()? Fairly certain we've moved beyond this as standard practice by this point; document.write isn't even valid if you're in an XHTML setting.

The best way to do this would be something like the following (also here, for better highlighting/parsing: https://gist.github.com/767131):

/*  Since script loading is dynamic/async, we take
    a callback function with our loadScript call
    that executes once the script is done downloading/parsing
    on the page.
*/
var loadScript = function(src, callbackfn) {
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.setAttribute("async", "true");
    newScript.setAttribute("src", src);

    if(newScript.readyState) {
        newScript.onreadystatechange = function() {
            if(/loaded|complete/.test(newScript.readyState)) callbackfn();
        }
    } else {
        newScript.addEventListener("load", callbackfn, false);
    }

    document.documentElement.firstChild.appendChild(newScript);
}

if(a) {
    loadScript("lulz.js", function() { ... });
} else {
    loadScript("other_lulz.js", function() { ... });
}

If you have jQuery or a similar library on the page, you can jack out my loadScript function and insert their appropriate function (ala $.getScript, etc).

Ryan McGrath
  • 1,974
  • 13
  • 22
3

You could do something like this:

var file=document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "script1.js")

Forgot to add that you need to then append this into an element on the page:

document.getElementsByTagName("head")[0].appendChild(file)
spinon
  • 10,086
  • 5
  • 36
  • 56
1
   <script type="text/javascript">     
    if(condition==true)
    {
        var src = "js/testing_true.js";
        var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.setAttribute("async", "true");
        newScript.setAttribute("src", src);
        document.body.appendChild(newScript);
    }else
    {

        var src = "js/testing_false.js";
        var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.setAttribute("async", "true");
        newScript.setAttribute("src", src);
        document.body.appendChild(newScript);
    }
</script>
pruthwiraj.kadam
  • 729
  • 7
  • 10
1

I used this and it works well:

<script type="text/javascript">
if(b_condition)
  document.write('<scri'+'pt src="http://script1.js"></'+'script>');
else
  document.write('<scri'+'pt src="http://scripts2.js"></'+'script>');
</script>

I see that document.write is not the best practice to use though, but it works. Any ideas better than this? I don't want to write so much code for something so simple.

Shafique
  • 1,756
  • 6
  • 24
  • 35
0

If the scripts are not huge and/or there is no other reason why not both should be loaded, I would do something like:

<script type="text/javascript" src="http://script1+2.js"></script>
<script type="text/javascript">
    if(b_condition) {
        functionA();
    } 
    else {
        functionB();
    }
</script>
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
0

You need to either emit the desired script block in your condition, or create the script tag using the DOM and insert it. http://ajaxpatterns.org/On-Demand_Javascript

moribvndvs
  • 40,946
  • 9
  • 129
  • 143
0

Those files script1.js and script2.js are your, or are u including them from another domain?

because if they are yours your can include both, and depends of your condition you can call functions inside the files..

Arthur Neves
  • 11,197
  • 8
  • 55
  • 72
0

This is usually a bad idea so I recommend that you tell us what you actually need to do so we can find a better solution for you. In general you would like to combine and minify all javascript needed on the page so the user only has to load it once.

If there is no other way than you can do it like this:

<script type="text/javascript">
    var script = document.createElement('script');
    if((b_condition){
        script.src = 'script1.js';
    }else{
        script.src = 'script1.js';
    }
    document.body.appendChild(script);
</script>
Wolph
  • 69,888
  • 9
  • 125
  • 143
-2
<?php if (a_condition) {?>
put html code here or script or whatever you like
<?php } elseif(b_condition) {?>
put any other code here 
<?php } else {?>
put even more code
<?php } ?>
-2
<script type="text/javascript">
   if(b_condition)
      document.write('<script type="text/javascript" src="http://script1.js"></script>');
   else
      document.write('<script type="text/javascript" src="http://script2.js"></script>');
</script>
alexwen
  • 1,118
  • 7
  • 16
  • Please don't advocate document.write() anymore, this is a horrible practice for performance because it blocks everything else while executing. – Ryan McGrath Jan 05 '11 at 22:05
  • as seen here (http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) it appears that its okay to use document.write in extremely simple cases like my example. disagree? – Shafique Jan 06 '11 at 15:59