bernhardh
bernhardh

Reputation: 3309

JS Asynchron script faild to execute

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)?

Upvotes: 0

Views: 314

Answers (1)

red-X
red-X

Reputation: 5128

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

Upvotes: 1

Related Questions