0

I want to include an adserver js script with javascript and load it async. But every try ends with an warning and the script isn't executed.

I get the following error message: "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."

I have tried to following variants:

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://example.com/test.js";
    document.body.appendChild(script);

Or I used the HTML Script attribute async

<script src="http://example.com/test.js" async></script>

But nothing worked, since the external script uses document.write. Is there another way to include such scripts?

How to "explicitly open" a page ("unless it is explicitly opened" - see warning)?

1 Answer 1

1

One way would be to overwrite document.write temporarily until the script is executed, afterwards replace original functionality.

var tempDocWrite = document.write;
document.write = function(el){
    var div = document.createElement('div');
    div.innerHTML = el;
    document.body.appendChild(div)
}

var script = document.createElement('script');
script.onload = function(){
    document.write = tempDocWrite
}
script.type = 'text/javascript';
script.src = "http://example.com/test.js";
document.body.appendChild(script);

note: have not tested the above code

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

3 Comments

Thank you. I get "Uncaught RangeError: Maximum call stack size exceeded". Btw. in line 3 you should repleace msg with el.
Oh great work! But I have another question based on your code. See jsfiddle example (it will not work, since jsfiddle don't allow document.write at all, but just for code formating) jsfiddle.net/02h6ss7h. How can I dynamically controll the position where the code is inserted. In your example, it is placed at the top of the page, in my example I added hardcoded the position in the function, but how can I use it with 2 differnt scripts, if I want to place script 1 in #top and script 2 in #middle?
@leftjustified that sounds like a completely different problem, I'd suggest you create a new question for that.

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.