Tag Archives: document

Asynchronous loading JS does not allow the use of document write solution

asynchronous loading js does not allow the use of document write solution

to recommend a cat smoking website: love cat family (http://15cat.com), I hope you like


var scriptFile = document.createElement('script');

scriptFile.setAttribute("type","text/javascript");

scriptFile.setAttribute("src",'http://api.map.baidu.com/api?type=quick&ak=o9B4Ol99j9NcBXSu5nFTR7uI&v=1.0');

document.getElementsByTagName("head")[0].appendChild(scriptFile);

When you finally want to add it to the head, chrome comes up with the following warning.
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.
What is this?
PS: An error in chrome in console (a red error mark) will prevent the script from executing after the error, a warning (yellow exclamation mark) just won’t execute where it was warned.

Solution.
This occurs because the code introduced contains a document.write method, and asynchronously loaded js is not allowed to use the document.write method.
Since the document has been loaded and parsed, the document stream is closed.
So the js you load asynchronously can no longer write into the document, such as using document.write.
So two direct links can be introduced.


var usel = '<script src="';
usel += gds[0].imageurl;
usel += '"></script>';
document.write(usel);