Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I load javascript code from a servlet before page loads

Status
Not open for further replies.

shreyasree

Programmer
Aug 31, 2007
6
US
Hi all,

I need to dynamically load javascript code from a servlet, without overwriting the existing page.

I tried the following methods, but they don't seem to help:

Method 1
I tried to load it after page loads, by creating
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.text = <javascript code obtained from servlet>
headID.appendChild(newScript);

This doesn't work probably because the obtained javascript has document.write.. which overwrites the existing page.

Method 2
I tried to include the javascript, by adding src as the servlet which returns the javascript code.
<script src=<path to servlet that returns the javascript code> type="text/javascript" language="javascript" ></script>

This gives a cross-site scripting error by the browser.

I need to load javascript code preferably before page loads, from a servlet. (Loading javascript after page loads would be fine too, if overwriting the existing page can be avoided)

It would be really great if you can help me figure this out!

Thanks!
Shreya
 
This doesn't work probably because the obtained javascript has document.write.. which overwrites the existing page.
Change it to not use document.write. Then it will work.

This gives a cross-site scripting error by the browser
Parse it server-side so it has the same domain as your site. Then it will work.

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
Thanks for your reply!

The javascript code is obtained from an external site. So, could you please further explain how to "Parse it server-side so it has the same domain as your site".

The following is what I am trying to achieve:

Client requests a specific page, (that includes a bootstrap javascript from the servlet) from Web Server A.
Web Server A requests Web Server B for the javascript.
Web Server B obtains javascript from an 'external' site and returns it to Web Server A.
WeB Server A returns the javascript code to client, which executes the javascript.

I would greatly appreciate your reply!

Thanks,
Shreya
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top