I'm having some concurrency issues with a webpage I'm building. Basically, I have three script files that I'm using to hold some data:
script1.js:
var myValue = 1;
script2.js:
var myValue = 2;
script3.js:
var myValue = 3;
And I have one page, mypage.html that basically looks like this:
<html>
<script>
function get_number()
{
var script_file = GetQueryStringValue( "run" );
e = document.createElement('script');
e.type='text/javascript';
e.src = script_file + ".js"
head.appendChild( e );
document.write( myValue );
}
</script>
<body onload="get_number()">
<div onclick="get_number()">Click me!</div>
</body>
</html>
The main idea with this page is that you would query it like this:
mypage.html?run=script1
which would tell the get_number()
function to dynamically insert script1.js
in to mypage.htm. Then, I call get_number()
to display the value loaded from the script.
Now, I've stripped down the above to what I think are the relevant parts and I've left out a bunch of stuff, obviously. My actual code loads a large array of values and is more interesting... But, I'm hoping someone can help me out with this regardless.
What I'm finding is that in IE, the number displays correctly.
In Firefox, Chrome and Safari, I get an error that myValue
is undefined. However, if I click the Click me
div that I created, the number displays correctly. So, I know I'm correctly loading the javascript external file. But, it just isn't loaded in time for my get_number()
function to work correctly onload
.
Now, I hacked up my file a little so that the get_number
function looks like this:
function get_number()
{
var script_file = GetQueryStringValue( "run" );
e = document.createElement('script');
e.type='text/javascript';
e.src = script_file + ".js"
head.appendChild( e );
setTimeout( function() { document.write( myValue ), 10 } );
}
The setTimeout delays enough for the DOM to be updated and the javascript to be loaded in most cases. But, this is a total hack. Firefox tends to load this 'improved' code correctly all the time while Chrome and Safari manage to get the value about 50% of the time.
So, I guess I'm wondering, is there a better way to accomplish what I'm trying to do here? It's very important that the value be driven externally (by the query string), but other than that requirement, I'm very flexible.
See Question&Answers more detail:
os