I have two files data1.js and data2.js
data1.js has a variable like
var rows = ['g1', 'g2'];
data2.js has a variable like
var rows = ['g1', 'g2', 'g3', 'g4'];
Initially, I am loading data1.js using
<script id="datascript" type="text/javascript" src="data1.js"></script>
However, on a button click I am loading data2.js with the hope of it loading its contents (i.e. updating the variable rows):
onclick="datascript.src='data2.js';alert(rows);"
However, my rows variable does not update. What am I missing?
Thanks
The problem is that you’re trying to read the value of the
rowsvariable before the second JS file is download and executed by your browser. To solve this:Use
jQuery.getScript()– http://api.jquery.com/jQuery.getScript/ – which provides a callback after the script is downloaded and executed.Code:
Or, if you wan to stick with pure JS, you can do:
Ref: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS