How to load third-party javascript tag asynchronously which has document.write

Kuldeep Kapade picture Kuldeep Kapade · Aug 28, 2015 · Viewed 9.2k times · Source

We give out a piece of javascript tags such as <script src="http://ours.com/some.js"></script> which site owners put on their site like http://example.com and in this javascript tag we want to dynamically include a third-party js such as which can have document.write in it, but of course if we try to include it by conventional method,

var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.src="http://third-party.com/some.js";
document.getElementById('target').appendChild(script_tag);

we get a warning from browser,

Warning: A call to document.write() from an asynchronously-loaded external script was ignored.

How do we get around this? Keep in mind, we don't really have control over third-party scripts so we can't change the logic in it. We are looking for some solution which can work across all browsers.

Answer

goncalotomas picture goncalotomas · Sep 7, 2015

The problem with loading a script on a already loaded document (instead of having the browser ignore the document.write()) is that you would delete all existent HTML. See this example so you can understand exactly what's happening, or for more details look at a documentation page for the document.write() method.

While I know this might not be what you're expecting to get as an answer, I believe you are out of luck since rewriting the script is not an option.

This appears to be a similar question with similar replies.