views:

44

answers:

3

Hi all,

When I write the following code directly into my html page under a script tag, the string "test" gets appended to my page without replacing the rest of its content (1):

document.write("test");

However, if I place that same code into a separate javascript file like (2):

<script src="http://127.0.0.1/whatever.js" type="text/javascript"></script>

Suddenly that same code rewrites my entire page.

Is there a way to perform a document.write() from a remote file and get the result in (1)?

Thanks for your time.

A: 

You may be including your script at the top of the page. Where it gets the document.write() stuff and thus writes the text instead of a append behaviour.

sushil bharwani
could you give me a proof of concept?
Benjamin
+2  A: 

If you use doc.write while the page page is rendering, it will insert or append the string. If you use doc.write after it's rendered, or after window.onload, it will essentially begin the rendering process again, and overwrite the page.

It's my guess that you are getting asynchronous behavior when loading the script, and it's not executing until after onload. I can't recreate your problem.

mwilcox
Thanks you actually found was what my problem and I could successfully fix it.
Benjamin
A: 

The safer solution is to append a document element to the page - that should always work

mplungjan