473,767 Members | 2,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loading Javascript with XMLHTTP...?

Using XMLHTTP and DOM I'm able to load new HTML page content.

I'd now like to load small snippets of javascript with the HTML markup
and have that <script> incorporated into the page. If any of the loaded
script exists outside a function definition (eg: a call to a function),
I'd like that code to be executed as soon as its added to the DOM.

Can anyone suggest the best way to do this? I've Googled but not found
anything comprehensive. Do I need to use the eval() method or is there
a better way?

Thanks,

Steve

Jul 26 '05 #1
10 4884
sn****@mxlogic. com wrote:
Using XMLHTTP and DOM I'm able to load new HTML page content.

I'd now like to load small snippets of javascript with the HTML markup
and have that <script> incorporated into the page. If any of the loaded
script exists outside a function definition (eg: a call to a function),
I'd like that code to be executed as soon as its added to the DOM.

Can anyone suggest the best way to do this? I've Googled but not found
anything comprehensive. Do I need to use the eval() method or is there
a better way?

Thanks,

Steve


The best way is to add a script element with a src attribute:

var oS = document.create Element('script ');
oS.type = 'text/javascript';
oS.src = 'someLink/cmd.js';

<URL:http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/f39a6a56185a49c 1/a4c3d5dcce0a08e 6?tvc=1&q=docum ent.createEleme nt(%27script%27 )&hl=en#a4c3d5d cce0a08e6>

But not all browsers may support the above. Also be careful of calling
functions in any linked file as they must be downloaded & added to the
document before they are ready to use. Adding a script element and then
depending on its content being immediately available is risky.

Any statements outside functions will be executed when the script is loaded.

AFAIK, you can't modify the content of a script element dynamically.
You can clone a script element that has statements outside functions and
add it to some part of the document, but the statements will not be
executed (at least not in Firefox or IE).
--
Rob
Jul 27 '05 #2
I may be wrong about this, but you may also need to set the "defer"
attribute to true.

oS.defer="true" ;

Jul 27 '05 #3

<sn****@mxlogic .com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Using XMLHTTP and DOM I'm able to load new HTML page content.

I'd now like to load small snippets of javascript with the HTML markup
and have that <script> incorporated into the page. If any of the loaded
script exists outside a function definition (eg: a call to a function),
I'd like that code to be executed as soon as its added to the DOM.

Can anyone suggest the best way to do this? I've Googled but not found
anything comprehensive. Do I need to use the eval() method or is there
a better way?

Thanks,

Steve


you could add a hidden iframe to your page,
and load whatever url you want into it.
at the bottom of the iframe page, put some
script that does something, such as call a
function on the main page.
Jul 27 '05 #4
Thanks Rob,

Actually, I've got the method you suggest working well in another area
of my code. The problem is when I load HTML content dynamically using
XMLHTTP -- how do I get the script added when it is received as
"responseTe xt" from the XMLHTTP request?

Perhaps I should parse the responseText and create new function
objects?

Hmm... tricky?

Steve

RobG wrote:
sn****@mxlogic. com wrote:
Using XMLHTTP and DOM I'm able to load new HTML page content.

I'd now like to load small snippets of javascript with the HTML markup
and have that <script> incorporated into the page. If any of the loaded
script exists outside a function definition (eg: a call to a function),
I'd like that code to be executed as soon as its added to the DOM.

Can anyone suggest the best way to do this? I've Googled but not found
anything comprehensive. Do I need to use the eval() method or is there
a better way?

Thanks,

Steve


The best way is to add a script element with a src attribute:

var oS = document.create Element('script ');
oS.type = 'text/javascript';
oS.src = 'someLink/cmd.js';

<URL:http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/f39a6a56185a49c 1/a4c3d5dcce0a08e 6?tvc=1&q=docum ent.createEleme nt(%27script%27 )&hl=en#a4c3d5d cce0a08e6>

But not all browsers may support the above. Also be careful of calling
functions in any linked file as they must be downloaded & added to the
document before they are ready to use. Adding a script element and then
depending on its content being immediately available is risky.

Any statements outside functions will be executed when the script is loaded.

AFAIK, you can't modify the content of a script element dynamically.
You can clone a script element that has statements outside functions and
add it to some part of the document, but the statements will not be
executed (at least not in Firefox or IE).
--
Rob


Jul 27 '05 #5
I suppose "eval" might work.

There is also a clue in RobG's answer.

var oScript=documen t.createElement ("script");
oScript.text=[[variable holding responseText]];
oScript.defer=" true";
document.getEle mentsById("head ")[0].appendChild(oS cript);

Jul 27 '05 #6
Thanks,

I think that's it :)

although I need to correct one line of your code...

document.getEle mentsById("head *")[0].appendChild(oS cript);

should read...

document.getEle mentsByTagName( "head*")[0].appendChild(oS cript);
Steve

Jul 27 '05 #7
Baconbutty wrote:
I suppose "eval" might work.

There is also a clue in RobG's answer.
Setting the text attribute of the script element does indeed add and run
the script as the OP requires - my test had a typo in the script that
caused it to fail (dang browser thinks 'javascript' and 'javscript' are
two different things).

var oScript=documen t.createElement ("script");
oScript.text=[[variable holding responseText]];
oScript.defer=" true";
document.getEle mentsById("head ")[0].appendChild(oS cript);


The defer attribute does not necessarily affect when the script is run,
it affects what the browser does while the script is loading and
executing. I would expect the browser to load the entire script before
executing any part of it.

A test is to have a statement at the very start of a script file that
calls a function at the very bottom of the file with a large amount of
guff in between - I've never seen this fail (maybe I just haven't used a
large enough file or slow enough connection) - though in practice I
ensure all functions are loaded first).

My reading of the HTML spec is that 'defer' tells the UA that it can
load the script element content asynchronously because it doesn't
generate any document content. In other words, don't defer
parsing/rendering the rest of the document until the script is loaded
(which is kinda contrary to what you might expect 'defer=true' to mean).

"When set, this boolean attribute provides a hint to the user agent
that the script is not going to generate any document content (e.g.,
no "document.write " in javascript) and thus, the user agent can
continue parsing and rendering."

<URL:http://www.w3.org/TR/html4/interact/scripts.html#ad ef-defer>

And in the index of attributes it says:

"UA may defer execution of script"

<URL:http://www.w3.org/TR/html4/index/attributes.html >

The second reference seems to contradict the first somewhat, maybe the
words 'while the rest of the document loads' should be added.

'defer' is probably only of use if the script is in the body of the
document or loaded from an external file and there is something else for
the UA to get on with while it loads and executes.
--
Rob
Jul 28 '05 #8
Good catch.

Typing too hastily.

Jul 28 '05 #9
Thanks Rob. I think I have been using it primarily as a precaution,
without really thinking about it.

Jul 28 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3351
by: warteschlange | last post by:
i want to postload javscript from another javascript. This works fine in firefox and IE6 for macIE i can use an Iframe to load the code and inject it with insertAdjacentHTML The problems arise with safari and opera. both load the new code with XMLHttpRequest, but the code is no 'executable' To make this possible on IE i had to use the magic 'DEFER' attribute.
1
3811
by: ozzy.osborn | last post by:
Hello All, I have been struggling with a cross browser solution to loading external javascript files on the fly. I have been successful using the following code in IE6: var newScr = document.createElement("SCRIPT"); newScr.src = "newScr.js"; newScr.type="text/javascript";
3
3471
by: SM | last post by:
Hello, Im trying to access elements in my XML file using the JavaScript DOM but i'm not sure how. I use AJAX to access the XML and then use the responseXML property to access the XML file data. I want to extract all the tracks from a specific CD. Right now, im using an array to stock all the data but its just a question of time before everything blows up because of the size of the array. Thats why im want to use an XML file (later i will...
6
10924
by: Shigun | last post by:
On a website I am working on I am trying to load another page into a div on the the page the user does his work from. What I have works correctly in FireFox, but not in IE. I've rummaged Google for quite a bit and found similar problems, but no actual solutions. Here is the JavaScript I have to load a URL into a Div: function setResponseHtml(pUrl, pDiv) { var lHttp = getHTTPObjectHtml(); var lUrl = pUrl; lUrl =...
20
4043
RMWChaos
by: RMWChaos | last post by:
Currently testing in: WinVista / IE7 I have been working on getting xmlhttprequest going for weeks now. I have finally gotten a semi-working script going. Pulling up text or xml files works great and populates into the webpage; however, executing javascript has a few problems: 1. Opens on a blank page, but not a new page. It appears to compeltely overwrite the original page. I want it to update the existing page by loading within a <div>...
2
1296
by: joe | last post by:
I am loading a text file to a variable with XMLHttpRequest() There seems to be some sort of timing issue since loadXML (source code below) returns the contents of the file on seconds try. In Firefox I get an empty string. No errors are reported. If I look at the code with Firefox debugger (Venkman) everything works fine. I should probably put a loop somewhere to check when loading the file is finished. var xmlhttp;
5
2597
by: TMN | last post by:
Hi All If I want to use an xml file to hold some config parameters for a web page do I need to load it with JS or is there a way of including it in the <head? Thanks Tim
1
2194
by: kout | last post by:
Hello. I'm trying to make some kind of image gallery with php and javascript (w/ ajax), but I've run into some problems. The basic idea is the following: I've got a <span> tag and, when I click a button, the inner html of the tag changes to <img src="x" />. The problem is that, unless the image is small -less than 80kB-, it won't load properly. Some browsers won't display it entirely, some others won't even show it. The code related to it:...
0
9405
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9841
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8838
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7383
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3930
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2807
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.