views:

119

answers:

2

Dear all,

I'm writing a webpage that relies on an external javascript file (that I have no control of), which returns data by using document.write's. Is there any way to dynamically call the function without it overwriting the whole document? Here's the most concise code I can think of:

<html>    
<head>
<script type="text/javascript">
    function horriblefunction () {
        document.write("new text");
    }
</script>
</head>

<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>

The idea beginning that without altering "horriblefunction()" (as it's external) the new text could be placed in the div instead of overwriting the page. Is this possible or does the function have to be called inside the div as the page is created?

Thanks for you help

A: 

Try using dynamic script loading from http://bezen.org/javascript/index.html

bezen.domwrite.js - Captures document.write and writeln for the safe loading of external scripts after page load.

Gary
This probably would work but requires the addition of another script so I went with the above answer. Thanks for your help though
PhilI
+2  A: 

The only way to use document.write after the page has finished rendering is to temporarily replace the function with one of your own making that will shove the content into a div. E.g.

function horriblefunction() { 
    var old_dw = document.write;
    document.write = function(text) { 
        document.getElementById( 'some_div' ).innerHTML = text;
    }

    // now call your external JS function that uses document.write

    document.write = old_dw;
}

This will work as long as the external JS is already loaded and you're just calling a function. If you need to load the JS (say, by inserting a new <script> tag into the DOM) remember that that operation is asynchronous, and you'll need to watch the DOM to know when it's safe to restore the old version of document.write.

friedo
`innerHTML` is a property, not a method.
Tim Down
This did the job admirably. It did have to load an external JS through a script tag and it took awhile to work out when to restore document.write.For those that want to know: I realised that document.write being called necessarily meant the script had finished, so if you add document.write = old_dw just below the getElementById line it restores the old document.write and there's no process-eating loop needed.@friedo - thanks once again
PhilI
@Tim thanks, I'll fix it. I've gotten too used to using jQuery's `html()` method
friedo