Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript IF/ELSE to call another JS Script?

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?

like image 751
Shafique Avatar asked Jan 05 '11 21:01

Shafique


People also ask

How do you call JS function from another JS file in HTML?

Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How do I link two JavaScript files?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.


1 Answers

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

like image 169
Ryan McGrath Avatar answered Oct 01 '22 15:10

Ryan McGrath