How to Execute Another JavaScript Script Using IF/ELSE Statement?

I am trying to dynamically call one of two JavaScript files based on a condition. Here is the code I have:

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

Unfortunately, this approach does not seem to work. Does anyone have any suggestions for how to properly make a conditional JavaScript call using an If/Else block?

Answer №1

Why is everyone suggesting the use of document.write()? It seems outdated and not recommended, especially in an XHTML setting.

A better approach would be something like the code snippet below (also available here for reference: 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 replace my loadScript function with their appropriate function (e.g., $.getScript).

Answer №2

One way to achieve this is by following these steps:

const newScript = document.createElement('script');
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "script1.js");

Don't forget to then insert this script into an element within the page:

document.getElementsByTagName("head")[0].appendChild(newScript);

Answer №3

This method has proven effective for me:

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

While I acknowledge that employing document.write may not be considered the optimal approach, it does get the job done. Are there more efficient alternatives available? I prefer to keep things simple and minimize the amount of code required for this task.

Answer №4


   <script type="text/javascript">
    if(condition)
    {
        var source = "js/testing_true.js";
        var scriptElement = document.createElement("script");
        scriptElement.type = "text/javascript";
        scriptElement.setAttribute("async", "true");
        scriptElement.setAttribute("src", source);
        document.body.appendChild(scriptElement);
    }
    else
    {
        var source = "js/testing_false.js";
        var scriptElement = document.createElement("script");
        scriptElement.type = "text/javascript";
        scriptElement.setAttribute("async", "true");
        scriptElement.setAttribute("src", source);
        document.body.appendChild(scriptElement);
    }
</script>

Answer №5

In cases where the scripts are not overly large and there are no other obstacles to loading both, one approach could be:

<script type="text/javascript" src="http://combined-scripts.js"></script>
<script type="text/javascript">
    if(condition) {
        doFunctionA();
    } 
    else {
        doFunctionB();
    }
</script>

Answer №6

It is essential to either output the specified script section within your condition or establish the script element using the Document Object Model (DOM) and incorporate it. Visit this link for more information.

Answer №7

Do you own the files script1.js and script2.js, or are you including them from a different domain?

If they belong to you, you have the option to include both and call functions inside the files based on your specific conditions.

Answer №8

It's not advisable to proceed this way, so it would be best if you could let us know the specific task at hand in order for us to provide a more suitable solution. Ideally, it is recommended to consolidate and compress all necessary javascript files on the webpage to minimize loading time for users.

If there are no alternative methods, you can follow this approach:

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

Answer №9

<script type="text/javascript">
   if(a_condition)
      document.write('<script type="text/javascript" src="http://first_script.js"></script>');
   else
      document.write('<script type="text/javascript" src="http://second_script.js"></script>');
</script>

Answer №10

<?php if (condition_one) {?>
insert your desired HTML or script content here
<?php } elseif(condition_two) {?>
add any other code in this section
<?php } else {?>
include additional code here
<?php } ?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

What method does jqGrid use to dynamically update the selection options list based on the status data?

Currently, I am utilizing jQgrid for displaying a list with data retrieved through Ajax. The list is displaying properly without any issues. However, my challenge lies in dynamically populating the list of options based on the status value received. Area ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

Get the hash value after a specific character using Javascript

I'm currently working on a website with ajax functionality where pages load when clicking on navigation buttons. However, I encounter issues when reloading the page as it defaults back to loading main.html, regardless of the URL. The hash being used i ...

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

Sort through a collection of objects depending on various criteria pulled from a separate array of objects

I am working with an array of objects called c, which looks like this: c = [ { name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', catego ...

Troubleshooting: Browser fails to update after CSSStyleRule modification using JavaScript

When making changes to CSS properties of elements using JS methods like CSSStyleSheet, insertRule, deleteRule, or CSSStyleRule.style.setProperty(), I noticed that the underlying CSS is updated but the page does not reflect these changes immediately. The c ...

Copying the position of one object to another in THREE.js does not function as expected

Recently I started experimenting with Three.js and I’m currently working on a project where I need to position a SpotLight at the same coordinates as the camera. Below is the code snippet I’m using: $(document).ready(function() { init(); }); func ...

Establishing standard emit actions in a Vue JS component layout

I am dealing with a complex situation involving two nested Vue JS components. The child component is emitting certain events to the parent function, which I have defined within the parent component declaration. The issue here is that these events are being ...

``There is an issue with the onsubmit property that prevents the opening of

I have encountered an issue with my forms that has me stumped. Despite searching online for help, I can't seem to figure out why my implementation is not working as intended. The concept is straightforward. I've embedded a form within a JSP page ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

Node.js - Locate a specific parameter within an array that is nested within a JSON object, and retrieve the remaining

I am working with a Node.js API call that returns a JSON object. My goal is to extract the customer's phone number from this object using a specific function, like body.result.reservations[X of reserv.].client.phone, and retrieve parameters such as p ...

ReactJS requires HTTP server to transpile babel code before running

I am a beginner when it comes to working with reactjs and I am currently in the process of setting up babel to execute babel code without having to serve HTTP files. Following the instructions on the Package Manager, I have successfully installed it along ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

getting value of object property using a function that is located within the same object

I am attempting to access the 'context' property (or specifically 'context.settings') from within the 'ready' function in the same object. I am uncertain of the correct syntax to achieve this. Below is the code snippet: modu ...

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

Utilizing the 'container' property in a React.js React-Bootstrap modal

How can I open a modal within a designated container using the native property "container"? Whenever I specify the class name of the container element, I encounter an error TypeError: Cannot use 'in' operator to search for 'current' in ...