473,326 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

dynamically add a script source

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
7 5025
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: The Pritchard | last post by:
I want the user to be able to save the information displayed on a dynamically created page. When I write a script like the following: <SCRIPT> winNew = window.open("","test");...
20
by: David | last post by:
I have a one-line script to add an onunload event handler to the body of the document. The script is as follows: document.getElementsByTagName("BODY").onunload=function s() {alert("s")} Now...
4
by: RobG | last post by:
I have a function whose parameter is a reference the element that called it: function someFunction(el) { ... } The function is assigned to the onclick event of some elements in the HTML...
2
by: christine.nguyen | last post by:
Hello all, I have a page called test.html. Within test.html I have an iframe whose source is mypage.html. When mypage.html loads, it dynamically creates a javascript element which contains a...
3
by: SGA Smele | last post by:
Hello, Now I think that there is a simple answer to my problem, but I don't know what it is and I can't work out what I should be searching for on the internet to read up some more about it. ...
5
by: jeet_sen | last post by:
Hi, My external javascript test.js contains a variable definition var a = "Hello,world!!"; I dynamically loaded the script test.js using the following fucntion: function loadScript(url) { var...
11
by: Daz | last post by:
Hello everyone. I am sure the answer to my question is simple, but I can't seem to dynamically add an onClick event to my script. I have a table which is generated dynamically, I am just...
4
windows_mss
by: windows_mss | last post by:
When I Select Source & Destination Dynamically, Path Getting Scatter Across The Map... hi, i can able to get the Correct Route and Path for the corresponding Source and destination, like...
2
by: sylver | last post by:
Hi, Following the discussion that can be found here:...
7
by: moksha | last post by:
Hi, I am new to javascript and i am facing a problem in coding. plz help me out. I am using javascript for dynamically creating a table row which contains text boxes and radio...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.