By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,384 Members | 1,829 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,384 IT Pros & Developers. It's quick & easy.

dynamically add a script source

P: n/a
cjl
Hey all:

I've searched the newsgroup, and googled, but I'm stuck. I want to be
able to 'dynamically' add a .js file to a web page after the page has
loaded, based on user interaction.

For example, the user make a choice by clicking on an item called
20050928, and as a result a file named "20050928/case.js" is
"included", and the data contained within is available.

The "data" files, in this example 20050928.js, contain several variable
assignments.

Can anyone point me in the right direction, or should I rethink my
webapp design?

-cjl

Oct 11 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
cjl wrote:
Hey all:

I've searched the newsgroup, and googled, but I'm stuck. I want to be
able to 'dynamically' add a .js file to a web page after the page has
loaded, based on user interaction.

For example, the user make a choice by clicking on an item called
20050928, and as a result a file named "20050928/case.js" is
"included", and the data contained within is available.

The "data" files, in this example 20050928.js, contain several variable
assignments.

Can anyone point me in the right direction, or should I rethink my
webapp design?


You can load script files by adding a script element and assigning an
appropriate value to the src attribute.

Ensure that the file is loaded before you try to use it. You can create
a suitable pause by having a user action select the file to load, then
another action to use the data. The pause between user actions gives
the browser time to load the file.

Another way to pause for the file to load is make the call to load the
file, then use setTimeout() to continue the script using a sufficient
lag to allow the script to load.

Neither are particularly robust since you don't know how long the file
will take to load.

Another (better?) option is to use XML and load the file using
document.implementation with Mozilla/Firefox or "Msxml.DOMDocument" with
IE. Then parse the file or use JSON or similar to convert the file to
objects that you can use.

It may be more work than you're prepared to do, and support is patchy
across browsers. Why not just load the data as a .js file when the page
loads? Even 20k of data would likely be OK provided you wait for the
page load to do stuff.
Here's a bit of sample code that works in Firefox and IE (but I make no
claims at all about its robustness) using a trivial XML file:

[XML file : data.xml]

<?xml version="1.0" encoding="iso-8859-1"?>
<arraydata>
<value>one</value>
<value>two</value>
<value>three</value>
</arraydata>

[XML]

[code]

<script type="text/javascript">

var X; // The use of a global can be avoided if not using IE

function loadXML(xmlFile)
{
var oLoadedXML;

// Mozilla et al
if( document.implementation && document.implementation.createDocument ) {
oLoadedXML = document.implementation.createDocument("","",null) ;
oLoadedXML.async=false;
var loaded = oLoadedXML.load(xmlFile);
if (loaded) {
X = parseXML(oLoadedXML);
}

// Internet Explorer
} else if( window.ActiveXObject && /Win/.test(navigator.userAgent) ) {
oLoadedXML = new ActiveXObject("Msxml.DOMDocument");
oLoadedXML.async = false;
oLoadedXML.onreadystatechange = function () {
if (oLoadedXML.readyState == 4) X = parseXML(oLoadedXML);
}
oLoadedXML.load(xmlFile);

// Code doesn't suit this browser
} else {
alert("Ooops, this script doesn't work in this browser.");
return;
}
}

function parseXML(oLoadedXML)
{
var allNodes = oLoadedXML.childNodes;
var i, j, x;
for (i=0, j=allNodes.length; i<j; i++){
x = allNodes[i];
if (x.tagName && 'arraydata' == x.tagName){
return parseArraydata(x);
}
}
return false;
}

function parseArraydata(n)
{
var x, i=0, dat=[];
for (var j=0, k=n.childNodes.length; j<k; ++j){
x = n.childNodes[j];
if (x.tagName && 'value' == x.tagName){
dat[i++] = x.firstChild.data;
}
}
return dat;
}

</script>

<input type="button" value="Load local file" onclick="
loadXML('data.xml');
alert(X);
">

[code]
--
Rob
Oct 11 '05 #2

P: n/a
cjl
RobG:
You can load script files by adding a script element and assigning an
appropriate value to the src attribute.
Two examples I have found:

script = document.createElement('script');
script.type= 'text/javascript';
script.src = 'scriptname.js';
document.getElementsByTagName('head')[0].appendChild(script);

And:

document.writeln('<SCRIPT SRC="' + variable + '.js">');
document.writeln('</SCRIPT>');
Ensure that the file is loaded before you try to use it. You can create
a suitable pause by having a user action select the file to load, then
another action to use the data. The pause between user actions gives
the browser time to load the file.
Someone in a previous thread suggested having the file you include set
a variable or call a function when it is loaded, but this is not
working for me.

In the last line of my "included" file, using the above techniques, I
call a function that is declared in the script that is "hard coded"
into the html page, but I'm getting an error that the function doesn't
exist. Should this work?

For example, the .js declared in the head of the document has a
function:

function preload(){
....do stuff
}

and the "included" file has:

....variable declarations
preload();

This doesn't work. Why?
Another (better?) option is to use XML and load the file using
document.implementation with Mozilla/Firefox or "Msxml.DOMDocument" with
IE. Then parse the file or use JSON or similar to convert the file to
objects that you can use.


I will try to wrap my head around your sample code later. Thanks.

-CJL

Oct 11 '05 #3

P: n/a
cjl said the following on 10/11/2005 6:20 AM:
RobG:

You can load script files by adding a script element and assigning an
appropriate value to the src attribute.

Two examples I have found:

script = document.createElement('script');
script.type= 'text/javascript';
script.src = 'scriptname.js';
document.getElementsByTagName('head')[0].appendChild(script);

And:

document.writeln('<SCRIPT SRC="' + variable + '.js">');
document.writeln('</SCRIPT>');


The first one is for use mostly after the page has loaded. The second is
used as the page is loading and will destroy the current page if used
after it is loaded.
Ensure that the file is loaded before you try to use it. You can create
a suitable pause by having a user action select the file to load, then
another action to use the data. The pause between user actions gives
the browser time to load the file.

Someone in a previous thread suggested having the file you include set
a variable or call a function when it is loaded, but this is not
working for me.


Of the two methods above, which are you using?
In the last line of my "included" file, using the above techniques, I
call a function that is declared in the script that is "hard coded"
into the html page, but I'm getting an error that the function doesn't
exist. Should this work?
For example, the .js declared in the head of the document has a
function:

function preload(){
....do stuff
}

and the "included" file has:

....variable declarations
preload();

This doesn't work. Why?


It depends on which method above you are using. If using the second,
then no preload() won't exist anymore. If using the first, post a URL to
a sample page.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 11 '05 #4

P: n/a
RobG said the following on 10/11/2005 2:24 AM:
cjl wrote:
Hey all:

I've searched the newsgroup, and googled, but I'm stuck. I want to be
able to 'dynamically' add a .js file to a web page after the page has
loaded, based on user interaction.

For example, the user make a choice by clicking on an item called
20050928, and as a result a file named "20050928/case.js" is
"included", and the data contained within is available.

The "data" files, in this example 20050928.js, contain several variable
assignments.

Can anyone point me in the right direction, or should I rethink my
webapp design?

You can load script files by adding a script element and assigning an
appropriate value to the src attribute.

Ensure that the file is loaded before you try to use it. You can create
a suitable pause by having a user action select the file to load, then
another action to use the data. The pause between user actions gives
the browser time to load the file.

Another way to pause for the file to load is make the call to load the
file, then use setTimeout() to continue the script using a sufficient
lag to allow the script to load.

Neither are particularly robust since you don't know how long the file
will take to load.


Put the function call that uses the just-loaded data at the end of the
..js file. It can't be called until it's loaded.

sample.js:

[code]

functionCall()

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 11 '05 #5

P: n/a
cjl
Randy:

Thank you for both of your posts. Both were very helpful.
It depends on which method above you are using. If using the second,
then no preload() won't exist anymore.
Aha! I was making that mistake.
Put the function call that uses the just-loaded data at the end of the
.js file. It can't be called until it's loaded.


Aha! I was making that mistake, too.

I made the changes based on the above information, and everything is
now working.

Just curious, why does the document.writeln method wipe out the
original function?

Thanks again.
CJL

Oct 11 '05 #6

P: n/a
cjl said the following on 10/11/2005 7:35 AM:
Randy:

Thank you for both of your posts. Both were very helpful.

It depends on which method above you are using. If using the second,
then no preload() won't exist anymore.

Aha! I was making that mistake.

Put the function call that uses the just-loaded data at the end of the
.js file. It can't be called until it's loaded.

Aha! I was making that mistake, too.

I made the changes based on the above information, and everything is
now working.

Just curious, why does the document.writeln method wipe out the
original function?


Because after the page is loaded, it is "closed" to writing. When you
document.write it explicitly calls the document.open() and then write's
to the page. In that process, it clears the current document and you get
the behavior you saw.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 11 '05 #7

P: n/a
Randy Webb wrote:
RobG said the following on 10/11/2005 2:24 AM:
cjl wrote:
Hey all:

I've searched the newsgroup, and googled, but I'm stuck. I want to be
able to 'dynamically' add a .js file to a web page after the page has
loaded, based on user interaction.

For example, the user make a choice by clicking on an item called
20050928, and as a result a file named "20050928/case.js" is
"included", and the data contained within is available.

The "data" files, in this example 20050928.js, contain several variable
assignments.

Can anyone point me in the right direction, or should I rethink my
webapp design?


You can load script files by adding a script element and assigning an
appropriate value to the src attribute.

Ensure that the file is loaded before you try to use it. You can
create a suitable pause by having a user action select the file to
load, then another action to use the data. The pause between user
actions gives the browser time to load the file.

Another way to pause for the file to load is make the call to load the
file, then use setTimeout() to continue the script using a sufficient
lag to allow the script to load.

Neither are particularly robust since you don't know how long the file
will take to load.

Put the function call that uses the just-loaded data at the end of the
.js file. It can't be called until it's loaded.


Yes, but care must be exercised when doing this, for example:

[data.js]

var remoteValue = 'Blah blah';
alert('File loaded... ' + remoteValue);

[HTML]

<input type="button" value="Add script element" onclick="
getValues('remoteValue');
">

<script type="text/javascript">
function addScript(uri)
{
var oScript = document.createElement('script');
oScript.src = uri;
var head = document.getElementsByTagName('head')[0];
head.appendChild(oScript);
}
function getValues(x)
{
addScript('data.js', x); // See alert 'File loaded... Blah blah'
alert(x); // Shows 'removeValue'
setTimeout('alert('+x+')',0); // Shows 'Blah blah'
}
</script>
So you must be careful how you use the remote file.
--
Rob
Oct 11 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.