Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 960
Kuldeep Kapade Avatar asked Aug 28 '15 00:08

Kuldeep Kapade


People also ask

How do you load third-party scripts dynamically in react?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.

Can I use async in script tag?

Note: The async attribute can only be used when JavaScript is linked externally to the HTML file. This is done using the src attribute of <script> tag.


1 Answers

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.

like image 155
goncalotomas Avatar answered Sep 22 '22 18:09

goncalotomas