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?
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With