Modify a JavaScript variable dynamically using an external source

I currently have two files named data1.js and data2.js. In data1.js, there is a variable defined as:

var rows = ['g1', 'g2'];

Whereas in data2.js, the variable is defined differently as:

var rows = ['g1', 'g2', 'g3', 'g4'];

Initially, I load data1.js using the following script tag:

<script id="datascript" type="text/javascript" src="data1.js"></script>

However, when a button is clicked, I try to load data2.js hoping it will update the variable rows with its contents:

onclick="datascript.src='data2.js';alert(rows);"

Unfortunately, despite changing the script source to data2.js, the rows variable does not update as expected. What could be causing this issue?

Thank you.

Answer №1

If you are encountering an issue where you are attempting to access the value of the rows variable before the second JavaScript file has been fully downloaded and executed by your browser, there is a solution:

You can utilize jQuery.getScript() - http://api.jquery.com/jQuery.getScript/ - which allows for a callback function to be triggered only after the script has been successfully fetched and run.

Code Example:

$('#datascript').remove();
$.getScript("data2.js", function(data, textStatus, jqxhr) {
   alert(rows);
});

Alternatively, if you prefer sticking to pure JavaScript, consider the following approach:

Reference:

// remove previous script element
var sElem = document.getElementById('datascript')
sElem.parentNode.removeChild(sElem);

// insert new script
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.id = 'datascript';
newScript.onload= function() {
   alert(rows);
};
newScript.src = 'data2.js';
document.getElementsByTagName("head")[0].appendChild(newScript);

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

Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you! let app = ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

Is it possible to sort an array by both date and time simultaneously?

As I work on developing a schedule app, it is necessary to sort items by both date and time simultaneously. In the current setup, the filtering only considers hours and minutes which is functional, but there is a need to also include dates in the sorting p ...

Using Javascript and ExtJS to retrieve the Codemirror Editor using a textarea

Hello to the wonderful stackoverflow community, I recently incorporated a Codemirror Editor into my ExtJSProject like this: addCodeMirrorPanel: function() { this.getAixmFormarea().add(Ext.widget({ xtype: 'textarea', fieldLabe ...

Jquery functionality fails to execute post-Ajax request

Here is the function in question: $(document).ready(function() { $('.post_button, .btn_favorite').click(function() { //Fade in the Popup $('.login_modal_message').fadeIn(500); // Add the mask to body $('body').append(' ...

Automatically reload a particular webpage upon closing a pop-up window (using jQuery)

I am facing an issue with a pop-up named PopUp1 on page0.aspx. The problem occurs when a user clicks on a row in the GridView within PopUp1, causing another pop-up to launch, loading my page1.aspx. The complication arises when the user navigates through l ...

The React material-table only updates and rerenders the table when the data is updated twice

Currently, I am utilizing a tool called material-table (check it out here: https://material-table.com/#/) which has been developed using React. The issue I am facing is that the data passed as a prop to material-table doesn't seem to update correctly ...

Using Ajax to dynamically load Wordpress post details and content into a designated div element

I have saved the post-id information in a data-* attribute, and I want to display this content within a div using the &.ajax() function. Below is the code I am currently working on: A list item displaying the post thumbnail <li class="homus-par ...

Node Pagination and Filtering feature malfunctioning

I am currently working on incorporating Pagination and Filtering in the backend functionality. This controller receives input such as Page number and Filtering conditions. Controller:- const getPosts = asyncHandler(async (req, res) => { const { ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

What is the process for cancelling an interval when it is disabled in my configuration file?

To automate a bot, I want it to stop running an interval if the configuration file specifies "off" and continue running if it says "on". I attempted this: Using discord.js: config.Interval = setInterval(() => { WallCheck.send(WallCheckemb ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...

The server is throwing a 403 error when trying to submit an AJAX request

I am currently working on a project similar to jsfiddle and encountering an issue during development. Whenever I attempt to make an ajax request with the JS alert() function in a text box, the server is returning a 403 error. Can anyone provide assistance ...

Activate the counter as soon as the error message appears

To effectively track the number of errors generated upon form submission, I require a counter mechanism. The errors are identified by the CSS class .validmissing. For instance, if a user encounters 5 errors upon submitting the form, the counter should be ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

javascript varying functionality between Chrome and Firefox

My Grease monkey script/Tamper monkey is designed to click on buttons that contain the word 'attach'. Although it works perfectly, I have noticed a difference in behavior between Chrome and Firefox. In Firefox, the clicks occur in the order of a ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...