1

Is there some way to load a js file that got document.write inside?

i.e:

(function(){

    var test = document.createElement('script');
    test.type="text/javascript";
    test.src="http://xxxxxxxxxxx/test.js";
    document.getElementsByTagName('head')[0].appendChild(test);

})();

test.js:

document.write('test !');

it always returns alert error about document.write async ...

I figured out if i do:

test.js:

document.getElementsByTagName('body')[0].innerHTML = 'test !';

it works !

but in my case i can't have access to js file, then i would like to know if is there a way to do it? or i'll need to do a cross with php curl.

thanks.

1
  • You could try to overwrite the document.write function before loading the script. Commented Jul 8, 2012 at 23:41

1 Answer 1

3

document.write() is designed for use while the document is being parsed. If you use it from a dynamically loaded script after the document has been loaded, then it will clear the current document and start writing a brand new document.

If you want to add content to the current document from a dynamically loaded script, then you should use DOM manipulation functions like document.createElement() and .appendChild() or .insertBefore(), not document.write().

Sign up to request clarification or add additional context in comments.

1 Comment

+1 – and to add further to that, the OP should read what HTML5 says about document.write, noting that it is not standardised and still very much implementation dependent (HTML5 essentially documents existing behaviour). However I think it goes a bit overboard with the warnings, document.write is very useful when used appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.