473,233 Members | 1,543 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,233 software developers and data experts.

Dynamical loading of html files and executing of its javascript content.

Hello Group,
i'm using a little "ajax" loader script to dynamically load files into
different "div" tags on my main site. the code for this part looks
like:

function loader() {
var args = loader.arguments;
switch (args[0]) { case
"load_page":
if (document.getElementById) {
var x = (window.ActiveXObject) ? new
ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); //create
xmlhttp object
}
if (x) {
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
el = document.getElementById(args[2]);
var viewData = x.responseText;
splitcode(el, viewData, args[2]);
}
}
x.open(args[3], args[1], true);
x.send(args[4]);
}
break;
}
}

i.e.: i call it through: loader('load_page', 'test/test.html', 'main',
'GET', 'null');

now, i want to get the javascript in test.html executed. for this
purpose i wrote splitcode(), which searches for <scripttags and
executes them.. this looks like:

function splitcode(el, viewData, id) {
var regexp1 = /<script(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig;
var regexp2 = /<script(.|\n)*?>((.|\n|\r\n)*)?<\/script>/im;
var regexp3 = /<script src(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig;
var regexp4 = /src.*\s\b/ig;

/* draw html first */
htmlpart = viewData.replace(regexp1, "");
el.innerHTML = htmlpart;

var result = viewData.match(regexp3);

if (result) {
for (var i = 0; i < result.length; i++) {
var srcScript = result[i].match(regexp4);
srcScript += "";
srcScript = srcScript.substr(5, srcScript.length-7);
var scriptContainer = document.createElement('SCRIPT');
var scriptContainerSrc = document.createAttribute('src');
var scriptContainerType = document.createAttribute('type');

scriptContainerSrc.value = srcScript;
scriptContainerType.value = "text/javascript";
scriptContainer.setAttributeNode(scriptContainerSr c);
scriptContainer.setAttributeNode(scriptContainerTy pe);

document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
}
}
var result = viewData.match(regexp1);

if (result) {
for (var i = 0; i < result.length; i++) {
var realScript = result[i].match(regexp2);
executeScript(realScript[2]);
}
}
}
function executeScript(scriptFrag) {
var scriptContainer = document.createElement('SCRIPT');
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
scriptContainer.text = scriptFrag;
}
This all works quite well within firefox. But for IE and Safari it
won't do at all! IE at least, lets me execute a function noted in
test.html once, but then it seems as if it has lost the javascript
code or can't find it again...

Any ideas to overcome this are greatly appreciated!

Moka Toka

May 30 '07 #1
13 2467
mo****@googlemail.com said the following on 5/30/2007 9:43 AM:
Hello Group,
i'm using a little "ajax" loader script to dynamically load files into
different "div" tags on my main site. the code for this part looks
like:
<snip<
now, i want to get the javascript in test.html executed. for this
purpose i wrote splitcode(), which searches for <scripttags and
executes them.. this looks like:
<URL:
http://groups.google.com/group/comp.lang.javascript/search?group=comp.lang.javascript&q=dynamically+sc ript+randy+webb+execute>

And start reading. Of those 62 hits, most are about exactly what you are
trying to do - execute scripts loaded in an HTML file after that HTML is
inserted into the document.
function splitcode(el, viewData, id) {
var regexp1 = /<script(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig;
var regexp2 = /<script(.|\n)*?>((.|\n|\r\n)*)?<\/script>/im;
var regexp3 = /<script src(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig;
var regexp4 = /src.*\s\b/ig;

/* draw html first */
htmlpart = viewData.replace(regexp1, "");
el.innerHTML = htmlpart;
Right here, rather than search the way you are, grab the script nodes of
the el element. Then it won't matter whether it has a source attribute
or inline scripts, you have the blocks. Then check them for src
attributes and code accordingly.

<FAQENTRY>

How do I execute scripts retrieved via AJAX?
</FAQENTRY>
That is there as a marker for myself and for comments from anyone who
has any thoughts/comments on the question.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 31 '07 #2
On May 31, 10:22 am, Randy Webb <HikksNotAtH...@aol.comwrote:
[...]
<FAQ***RY>

How do I execute scripts retrieved via AJAX?
</FAQ***RY>
That is there as a marker for myself and for comments from anyone who
has any thoughts/comments on the question.
Great idea. Since you suggested it, I'll give you the standard FAQ
maintainer response: post your best effort for criticism and see what
eventuates. ;-)
--
Rob

May 31 '07 #3
dd
On May 30, 3:43 pm, mow...@googlemail.com wrote:
function executeScript(scriptFrag) {
var scriptContainer = document.createElement('SCRIPT');
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
scriptContainer.text = scriptFrag;
}
You should be setting the .text attribute of the scriptContainer
before it gets appended to the head.

May 31 '07 #4
Hey, i already responded but it doesn't show up.... so i just post it
again:

that's what i use now:

function executeScript(scriptFrag) {

var scriptContainer = document.createElement('SCRIPT');

if(document.createTextNode("test")) {
var s = document.createTextNode(scriptFrag);
scriptContainer.appendChild(s);
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
} else {
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
scriptContainer.text = scriptFrag;
}
}

This at least works for Safari and Firefox on my Mac. IE seems to hang
on the regexp, it returns "null" where there should be the <script>
tag..
> var regexp3 = /<script src(.|\n)*?>(.|\n|\r\n)*?<\/script>/ig;
Right here, rather than search the way you are, grab the script nodes of
the el element. Then it won't matter whether it has a source attribute
or inline scripts, you have the blocks. Then check them for src
attributes and code accordingly.
So Randy, could you explain to me howto grap them your way?
Thanks,
Moka

May 31 '07 #5
so well, it's me again :) i think i got what you mean. splitcode now
looks like:

function splitcode(el, viewData, id) {

el.innerHTML = viewData;

var scriptNodes = el.getElementsByTagName('script');

var scriptCount = scriptNodes.length;


for (var i = 0; i < scriptCount; i++) {

var scriptFile = false;
var scriptNode = scriptNodes[i];

for (var j=0; j < scriptNode.attributes.length; j++) {
if (scriptNode.attributes[j].nodeName == "src")
scriptFile = true;
}

if (scriptFile) {
var scriptContainer = document.createElement('SCRIPT');
var scriptContainerSrc = document.createAttribute('src');
var scriptContainerType = document.createAttribute('type');

scriptContainerSrc.value =
scriptNode.attributes['src'].nodeValue;
scriptContainerType.value =
scriptNode.attributes['type'].nodeValue;

scriptContainer.setAttributeNode(scriptContainerSr c);
scriptContainer.setAttributeNode(scriptContainerTy pe);

document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
}
else {
var scriptContainer = document.createElement('SCRIPT');
var scriptFrag = scriptNode.firstChild.nodeValue;

if(document.createTextNode("test")) {
var s = document.createTextNode(scriptFrag);
scriptContainer.appendChild(s);
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
} else {
document.getElementsByTagName("head")
[0].appendChild(scriptContainer);
scriptContainer.text = scriptFrag;
}
}
}
}
and, guess what?! safari returns 0 for scriptNodes.length; (should be
2, FF works well).

frustrated,
moka

May 31 '07 #6
RobG said the following on 5/31/2007 5:32 AM:
On May 31, 10:22 am, Randy Webb <HikksNotAtH...@aol.comwrote:
[...]
><FAQ***RY>

How do I execute scripts retrieved via AJAX?
</FAQ***RY>
That is there as a marker for myself and for comments from anyone who
has any thoughts/comments on the question.

Great idea. Since you suggested it, I'll give you the standard FAQ
maintainer response: post your best effort for criticism and see what
eventuates. ;-)
I have bits and pieces of it together working on it. I posted that
mostly as a reminder to myself to post it to the group when I get it
close enough to encounter 80% or so of the criticism it will get :)

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 31 '07 #7
On May 31, 10:20 pm, mow...@googlemail.com wrote:
so well, it's me again :) i think i got what you mean. splitcode now
looks like:

function splitcode(el, viewData, id) {

el.innerHTML = viewData;

var scriptNodes = el.getElementsByTagName('script');
innerHTML has quirks in various browsers. If you are adding HTML to a
page using innerHTML (often as a response to an XMLHttpRequest) that
includes script elements, the most common method is to strip out the
script elements first, add the HTML and then:

- For script elements that contain text (i.e. code) use eval to run
it
- For script elements have a viable scr attribute value, use that to
add the script

The trick with eval is that it changes the scope of the eval'd
scripts, but that can be dealt with. The issue with stripping out the
script elements means they run after all the HTML has been added, so
if you expect them to to run as the HTML goes in you may have a
problem.

The topic has been covered here before at length:

<URL:
http://groups.google.com.au/group/co...1557c29ed3dfde
>
There are many useful links in that thread.
--
Rob

May 31 '07 #8
el.innerHTML = viewData;
>
innerHTML has quirks in various browsers. If you are adding HTML to a
page using innerHTML (often as a response to an XMLHttpRequest) that
includes script elements, the most common method is to strip out the
script elements first, add the HTML

and how do you add the HTML, if not with .innerHTML?

and then:

- For script elements that contain text (i.e. code) use eval to run
it

i've read through eval sometimes, and the most common opinion was:
eval = evil!
dunno really why though, could you explain the disadvantage of using
it?
.... and how would you strip the <scripttags out? with regexp in my
first post?
or loading the whole thing into a div, strip and save them out, and re-
put them into again?
thanks alot,
moka

Jun 1 '07 #9
i forgot to append: the javascript should be available all the time
after loading the page. there are functions which get called more than
once on loading. as i understand the eval function, my js code only
gets executed once, while my loader evals it. but not, if i click on
the loaded pages' button which should execute it too?!

any suggestions?

moka
Jun 1 '07 #10
mo****@googlemail.com said the following on 6/1/2007 4:49 AM:
>> el.innerHTML = viewData;
>innerHTML has quirks in various browsers. If you are adding HTML to a
page using innerHTML (often as a response to an XMLHttpRequest) that
includes script elements, the most common method is to strip out the
script elements first, add the HTML


and how do you add the HTML, if not with .innerHTML?
>and then:

- For script elements that contain text (i.e. code) use eval to run
it
i've read through eval sometimes, and the most common opinion was:
eval = evil!
dunno really why though, could you explain the disadvantage of using
it?
It is slow, inefficient, and opens up a page to malicious attacks.

The disadvantage with eval is that it changes the scope of
variables/functions.
... and how would you strip the <scripttags out? with regexp in my
first post?
I wouldn't, but that is my personal choice.
or loading the whole thing into a div, strip and save them out, and re-
put them into again?
Insert your HTML chunk with innerHTML into a "containerDiv" and then
loop through them:

var container = document.getElementById('containerDiv')
var allNewScripts = container.getElementsByTagName('script')

And then loop through the allNewScripts collection. If it has a src,
create a script element with a src attribute. If it doesn't have a src
attribute, you set the text property of a new script element.

It doesn't directly answer your question, but, the main problem is that
you are trying to insert code/content into another page that was never
intended to be inserted that way. For an "AJAX site" to be efficient and
actually capitalize on the speed gains then the backend *must* be set up
to generate content that is optimized for the front end.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jun 2 '07 #11
Randy Webb wrote on 02 jun 2007 in comp.lang.javascript:
It doesn't directly answer your question, but, the main problem is that
you are trying to insert code/content into another page that was never
intended to be inserted that way. For an "AJAX site" to be efficient and
actually capitalize on the speed gains then the backend *must* be set up
to generate content that is optimized for the front end.
I totally agree with you, Randy.

The fact remains
that AJAX as such is a typical example of using the web
and clientside javascript as it was not intended.

;-)

The nice thing about programming in general
is it's flexability to do things that where not intended
by the programmers.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 2 '07 #12
Evertjan. said the following on 6/2/2007 11:35 AM:
Randy Webb wrote on 02 jun 2007 in comp.lang.javascript:
>It doesn't directly answer your question, but, the main problem is that
you are trying to insert code/content into another page that was never
intended to be inserted that way. For an "AJAX site" to be efficient and
actually capitalize on the speed gains then the backend *must* be set up
to generate content that is optimized for the front end.

I totally agree with you, Randy.

The fact remains
that AJAX as such is a typical example of using the web
and clientside javascript as it was not intended.
Using it for anything other than secondary features, or, are you
referring to using javascript to load complete documents to insert into
a container? If the first, then I disagree with you as javascript may
have started out as an option for additional features but it has almost
become a de facto necessity for it to be enabled for most of the web. It
is moving closer and closer to mandatory and not the other way around.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jun 3 '07 #13
Randy Webb wrote on 03 jun 2007 in comp.lang.javascript:
Evertjan. said the following on 6/2/2007 11:35 AM:
>Randy Webb wrote on 02 jun 2007 in comp.lang.javascript:
>>It doesn't directly answer your question, but, the main problem is
that you are trying to insert code/content into another page that
was never intended to be inserted that way. For an "AJAX site" to be
efficient and actually capitalize on the speed gains then the
backend *must* be set up to generate content that is optimized for
the front end.

I totally agree with you, Randy.

The fact remains
that AJAX as such is a typical example of using the web
and clientside javascript as it was not intended.

Using it for anything other than secondary features, or, are you
referring to using javascript to load complete documents to insert
into a container? If the first, then I disagree with you as javascript
may have started out as an option for additional features but it has
almost become a de facto necessity for it to be enabled for most of
the web. It is moving closer and closer to mandatory and not the other
way around.
I think AJAX or something like it should become mainstream to clientside
javascript by having a set of simple commands that can be cross browser
compatible.

In the main time the using of javascript engine external xmlhttp-like
functions is a necessity, BECAUSE such in-page client/server
communication was never forseen at the present javascript implementation
stages.

A multitasking ability of these in-page client/server communication
capable browsers will become a necessity, since the "pointless" waiting
for a single AJAX communication to complete [or abort] even[?] breaks up
Googles complex interactivity efforts.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 3 '07 #14

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

Similar topics

4
by: hoke | last post by:
I want to display plain text files in the browser. The files contain html and javascript and have a .txt extension. This works fine with files with just html. Unfortunately when showing files with...
5
by: Treetop | last post by:
I have noticed with various codes that the slashes are not consistent. Is there a reason for this. For example </td> </\td> <\/td> <td /> what is the difference with these tags?
5
by: MK | last post by:
Dear friends, I have many HTML files and they all have some common HTML code which is basically bunch of tags which are in all the files. How can I put the common code in one file and then share...
2
by: Ben Amada | last post by:
Hello, A partner is going to be creating some HTML files that I plan on converting to user controls (UC) and dynamically load at runtime. I'm guessing Visual Studio doesn't come with some...
2
by: David Virgil Hobbs | last post by:
Loading text strings containing HTML code into an HTML parser in a Javascript/Jscript I would like to know, how one would go about loading a text string containing HTML code, so as to be able to...
1
by: isha.mackker | last post by:
How can html files be loaded dynamically through javascript? Can and how a link , which may be in a third party web page, or a bookmark button can be programmed in javascript to load another web...
2
by: D`Jinn Deegee | last post by:
I have 5 html files say file1.html file2.html : : file5.html Now I have another html file (main.html) where I want to use 1 html
0
by: vinayakk | last post by:
Hello webies, I have a problem with loading html pages in frameset. I am using location.href to load html pages one by one upon the user request and these pages in turn load flash files. When one...
10
by: paulie | last post by:
Hi, I have been experiencing an issue when trying to use AJAX to reload a DIV area using a timer of 2000ms, which contains a html page with another DIV and javascript. Scenario -------------...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
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
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
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...

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.