异步加载js不允许使用document write的解决方法
ps:本人亲测,阿里云2核4G5M的服务器性价比很高,新用户一块多一天,老用户三块多一天,最高可以买三年,感兴趣的可以戳一下:阿里云折扣服务器
代码:
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);
最后要添加到head里的时候,chrome出现以下警告:
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.
这怎么回事,何解?
PS:chrome中console里的错误(一个红色错号)会阻止错误之后的脚本执行,警告(黄色叹号)只是被警告的地方不会执行。
解决方法:
出现这个的原因是引入的代码中包含了document.write方法,异步加载的js是不允许使用document.write方法的。
因为document已经加载解析完毕,文档流已经关闭了
所以你异步加载的js不可以再往document里写东西了,比如使用document.write
所以直接引入两个链接就可以了:
var usel = '<script src="';
usel += gds[0].imageurl;
usel += '"></script>';
document.write(usel);