/    Sign up×
Community /Pin to ProfileBookmark

Open .js file, read contents, close file, open another .js file…

Hello everyone,

First of all, let me say hello to you all in my first post as a member of Webdeveloper.com. It is not likely I’ll be able to maintain a lot of activity here – I’m very active in a number of discussion groups, and my time is exceptionally limited. But I’m a great believer in the power of collaborative knowledge, and I’m hoping there are enough similar-minded people here who can help me with a very complex JavaScript issue I’m having at the moment. So here goes!

I’m about 95% of the way done programming an e-learning module system, done completely through XHTML, CSS and JavaScript. It must be done through JavaScript, because the contents of the system need to be downloadable and executed from individual PCs, but compiling is not an option either. So, JavaScript is the solution.

Here’s where I’m running into problems. I am attempting to automatically generate the tags necessary to open a connection to various .js files. I need to be able to dynamically generate the following: <script type=”text/javascript” src=”path[b]1[/b]/file.js”></script>, retrieve the contents of an array within the .js file, and assign those array contents to a global array with a unique name. Then, I need to open <script type=”text/javascript” src=”path[b]2[/b]/file.js”></script>, pull the contents of an array with the exact same name, and assign the array values to a second unique, global array. And so on and so forth, using a do while loop.

I’ve gone so far as to generate the code that links to each .js file, but how do I make it so this generated <script> link actually functions, instead of just being a non-functional string? I need it to be recognized by the browser as HTML, pull values from the location specified, then replace it with another path, recognize it as HTML, pull values again, etc.

Does this make any sense?

to post a comment
JavaScript

20 Comments(s)

Copy linkTweet thisAlerts:
@TheBearMayFeb 03.2006 — What has worked for me in the past is placing an id on the js tag and then changing the src as needed, ie:
<i>
</i>&lt;script id="multiPath" src="path1/file.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
...
document.getElementById("multiPath").src="path2/file.js";
...
&lt;/script&gt;
Copy linkTweet thisAlerts:
@the_pmauthorFeb 03.2006 — Ooh, I never thought of applying DOM to this script. Very nice. I'll give it a try right now ?

(OT, I used to date a girl from Worthington...).
Copy linkTweet thisAlerts:
@the_pmauthorFeb 03.2006 — Hmm, I'm not getting it to work right. Here's some code, for more insight:

&lt;script type="text/javascript" id="scriptLocation" src=""&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
Topics=new Array("Introduction","Features","Competition","Positioning");
var def = 0
var xyz = Topics.length

var srces = ""
do {
srces = Topics[def] + "/topic_vars.js";
document.getElementById('scriptLocation').src = srces;
alert(srces);
alert(document.getElementById('scriptLocation').src);
alert(TopicTitle);
def++;
} while (def != xyz);
&lt;/script&gt;
TopicTitle is a variable defined on every topic_vars.js page being specified using the Topics array to create the folder path. If this is working properly, the Alert box containing the value TopicTitle will show a different value, corresponding to the different path that's being generated with each loop.

But for some reason, TopicTitle is an empty string. In my mind, the logic says the code above should work, but obvoiusly something either isn't written properly, or what I'm trying to do simply can't be done (browser states, or something to that effect).

Any thoughts, given this additional information?
Copy linkTweet thisAlerts:
@TheBearMayFeb 06.2006 — Looks like it should work - may have to load an initial src value though. Working off another PC at the moment. Will check this out when I get to my "home" PC.
Copy linkTweet thisAlerts:
@the_pmauthorFeb 06.2006 — I thought that as well, and I tried it with an initial value in place. It simply read the variable from the initial src four times, never pulling it from the other three sheets in the array.

Thanks for looking into this! I'll put together a working version of the non-woring script for testing purposes.
Copy linkTweet thisAlerts:
@the_pmauthorFeb 06.2006 — Here's a test environment to see it in action...erm...in inaction ?

http://www.paulhirsch.com/ex/JavaScript_Issue/help.html - the file running the script

http://www.paulhirsch.com/ex/JavaScript_Issue/ - the folder in which everything resides

http://www.paulhirsch.com/ex/JavaScript_Issue/help.zip - the entire test environment

Thanks for looking at this! And thanks in advance to anyone else who is able to give some insight ?
Copy linkTweet thisAlerts:
@gphFeb 06.2006 — here's another technique

<i>
</i>function newScript(script_src){
var script=document.createElement('script');
script.type='text/javascript';
script.src=script_src;
document.getElementsByTagName('head')[0].appendChild(script)
}
Copy linkTweet thisAlerts:
@the_pmauthorFeb 06.2006 — Nice, gph. I'll give that a try! We're delving into areas where I'm rather unfamiliar. This will be an interesting exercise.

I'm wondering whether this will allow each extraction to take place within the proper document. The problem before wasn't with opening documents, it was with extracting from multiple ones, given the same variable name within each one. If your technique works...

?
Copy linkTweet thisAlerts:
@gphFeb 06.2006 — Oh I see, I just skimmed the thread.

maybe something like this (pseudo code)

myVar = null

open and read script

myVar = null

open and read script

...
Copy linkTweet thisAlerts:
@the_pmauthorFeb 06.2006 — Oh I see, I just skimmed the thread.

maybe something like this (pseudo code)

myVar = null

open and read script

myVar = null

open and read script

...[/QUOTE]

But would it do any good to declare myVar = null everytime? Doesn't open and reading the script just overwrite the value anyway?
Copy linkTweet thisAlerts:
@gphFeb 06.2006 — Yes it does, I just tested that as I thought it was the problem. Now I'm confused. Sorry but could you reexplain the issue?
Copy linkTweet thisAlerts:
@the_pmauthorFeb 06.2006 — Hmm, I'm trying to think of how else I can explain it...

Did you have a chance to view this page - http://www.paulhirsch.com/ex/JavaScript_Issue/help.html ? You can see the expected outcome in the top box. This is hard coded into place. You can see the dynamically generated code in the second box. I purposefully removed the do while loop that causes the script to make the attempt at changing the script src, so you can see how the dynamic generation works.

When I add the loop, this is when it all comes apart. The loop is opening a different .js document from the one that is originally set in the code and attempting to extract information from it. But it won't do it. It refuses to recignize the replacement document's variables, instead defaulting to the first document, or, depending on how I call it, declaring the variables null.

That's the gist of it.
Copy linkTweet thisAlerts:
@gphFeb 07.2006 — The 2nd script block in help.html is looping improperly. You need to reset def to 0 with each pass through the outside loop.
<i>
</i>&lt;script type="text/javascript"&gt;
abc = 0;
def = 0;
uvw = database.length;
xyz = Topics.length;
list = "";
stripme = "";
code = "";
do {
document.getElementById('scriptLocation').src = Topics[abc] + "/topic_vars.js";

<i> </i>do {
<i> </i> stripme = database[def].replace(/_/g," ")
<i> </i> // alert(stripme);
<i> </i> list = list + "&lt;li&gt;Subtopic: " + stripme.replace(/.html/g,"") + "&lt;/li&gt;"
<i> </i> // alert(list);
<i> </i> def++;
<i> </i>} while (def != uvw);
<i> </i>code = code + "&lt;h3&gt;Topic &lt;a href="" + Topics[abc] + "/"&gt;" + TopicTitle + "&lt;/a&gt;&lt;/h3&gt;&lt;ul&gt;" + list + "&lt;/ul&gt;";
<i> </i>// alert(code);
<i> </i>abc++;
<i> </i>[COLOR=red]def=0;[/COLOR]
} while (abc != xyz);
document.write(code);
&lt;/script&gt;


But the main problem is that it needs time to download the script files.

Try this with no other scripts in the page. If you uncomment the first alert it fails, the 2nd using setTimeout works
<i>
</i>function newScript(script_src){
var script=document.createElement('script');
script.type='text/javascript';
script.src=script_src;
document.getElementsByTagName('head')[0].appendChild(script)
}
newScript("Features/topic_vars.js")
//alert(database);
setTimeout('alert(database)',1)


So what you need to do is download the script then

setTimeout('myFunc()',100) <-- 100 to be safe.

Finally in myFunc() run the loops using DOM or innerHTML to write the text
Copy linkTweet thisAlerts:
@the_pmauthorFeb 07.2006 — Thanks for catching my mistake regarding var def. In addition, I also had to reset var list to null too, right in the same spot.

I've update the zip file and the help.html page to reflect these changes, and the script is doing everything is should...except pulling data from the right source .js documents ?

I haven't done the second part yet, so I'm off to do it now. I just thought I'd give a little progress report and thank you for handling my oversight ?
Copy linkTweet thisAlerts:
@the_pmauthorFeb 07.2006 — Ok, it took a [i]hell[/i] of a lot of doing, but I finally managed to sort this, thanks 90% to gph and 10% to pure luck ?

I can't post a link to the page with the final answer, because your browser will parse out the source and eliminate all traces of the code. So here it is. If you've downloaded the .zip I provided above and you create a new HTML page using the following code, you'll see everything works great!

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;
&lt;title&gt;JavaScript Issue&lt;/title&gt;
&lt;script type="text/javascript" src="global.js"&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body onload="dothis();"&gt;

&lt;div id="scriptsHere"&gt;
&lt;script type="text/javascript" id="scriptLocation" src="Introduction_to_This_Product/topic_vars.js"&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;
var abc = 0;
var def = 0;
var uvw = database.length;
var xyz = Topics.length;
var list = "";
var stripme = "";
var code = "";
var script = "";
var codeFinal = "";

function dothis() {
if (abc != xyz) {
script = document.createElement('script');
script.type = 'text/javascript';
script.src = Topics[abc] + "/topic_vars.js";
document.getElementById('scriptsHere').appendChild(script);
setTimeout('dothat()',100);
} else {
codeFinal = "&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;n&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;n&lt;head&gt;n&lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;n&lt;title&gt;JavaScript Issue&lt;/title&gt;n&lt;/head&gt;n&lt;body onload="dothis();"&gt;nn&lt;div style="border:2px solid #0C0"&gt;&lt;div style="margin:10px"&gt;n" + code + "&lt;/div&gt;&lt;/div&gt;nn&lt;/body&gt;n&lt;/html&gt;";
document.write(codeFinal);
}
}

function dothat() {
do {
uvw = database.length;
stripme = database[def].replace(/_/g," ");
list = list + "t&lt;li&gt;Subtopic: " + stripme.replace(/.html/g,"") + "&lt;/li&gt;n";
def++;
} while (def != uvw);
code = code + "&lt;h3&gt;Topic &lt;a href="" + Topics[abc] + "/"&gt;" + TopicTitle + "&lt;/a&gt;&lt;/h3&gt;n&lt;ul&gt;n" + list + "&lt;/ul&gt;n";
abc++;
def = 0;
list = "";
dothis();
}
&lt;/script&gt;
&lt;/div&gt;&lt;/div&gt;


&lt;/body&gt;
&lt;/html&gt;
I need to do some clean up, to make my markup a little purtier, but all in all, this has been a successful venture and a great learning experience. Thanks for your help, both of you!

  • - Paul
  • Copy linkTweet thisAlerts:
    @the_pmauthorFeb 07.2006 — Ok, so things aren't sorted out as nicely as I'd hoped.

    If you create the page I put up in my previous post and run it within the context of the test environment I created, you'll see that the 'codeFinal' variable overwrites the entire page, which is definitely not what I had in mind. I added all of the page information to the variable because it was doing this, but I would greatly prefer it if I could simply return the contents of the 'code' variable within the existing page.

    The reason for this is I'm running into some major problems when attempting to call more remote scripts with markup inside the 'codeFinal' variable. Frankly, I'd rather not have to rewrite the entire page either way, but the additional .js file inclusion issue is a dealbreaker if I can't sort it.

    Any thoughts on this?
    Copy linkTweet thisAlerts:
    @gphFeb 08.2006 — I'll have a look at this in about 2 hours.

    Note that document.write() writes to the page before the onload event. After the onload event, it overwrites the entire document.
    Copy linkTweet thisAlerts:
    @gphFeb 08.2006 — Something like this.

    <i>
    </i>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
    &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;
    &lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;
    &lt;title&gt;JavaScript Issue&lt;/title&gt;
    &lt;script type="text/javascript" src="global.js"&gt;&lt;/script&gt;

    &lt;script type="text/javascript"&gt;

    var code = "";

    window.onload=function(){
    var i=0,xyz=Topics.length,breather=100;
    while(i&lt;xyz){
    setTimeout('dothis('+i+')',breather);
    breather+=100;
    i++
    }
    setTimeout('wrtieIt()',breather)
    }

    function wrtieIt(){
    code = '&lt;div style="border:2px solid #0C0"&gt;&lt;div style="margin:10px"&gt;' + code + '&lt;/div&gt;&lt;/div&gt;';
    document.getElementsByTagName('body')[0].innerHTML=code
    }

    function dothis(i) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = Topics[i] + "/topic_vars.js";
    document.getElementsByTagName('head')[0].appendChild(script);
    setTimeout('dothat('+i+')',50);
    }

    function dothat(i) {
    var def = 0,uvw = database.length,list = "";
    do {
    list += "&lt;li&gt;Subtopic: " + database[def].replace(/_/g," ").replace(/.html/g,"") + '&lt;/li&gt;';
    def++;
    } while (def != uvw);
    code += '&lt;h3&gt;Topic &lt;a href="' + Topics[i] + '"&gt;' + TopicTitle + '&lt;/a&gt;&lt;/h3&gt;&lt;ul&gt;' + list + '&lt;/ul&gt;';
    }
    &lt;/script&gt;

    &lt;/head&gt;
    &lt;body&gt;
    &lt;/body&gt;
    &lt;/html&gt;

    Notice that I changed all the html strings to single quotes. If you do it that way you don't need to escape all the double quotes in the HTML.
    Copy linkTweet thisAlerts:
    @the_pmauthorFeb 08.2006 — Thanks gph! I'll test the innerHTML method in the live version of the application tomorrow when I'm back on my work computer.

    Thanks for all of your help. I'm looking forward to delivering good news ?
    Copy linkTweet thisAlerts:
    @the_pmauthorFeb 08.2006 — And the results are in. It's perfect! Thanks again gph. I've nveer used innerHTML. I've never needed to use it before. Now I see how useful it can be.

    This sucker is SORTED ?
    ×

    Success!

    Help @the_pm spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.26,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...