首页 > 用原生js怎么动态添加一个js文件?

用原生js怎么动态添加一个js文件?

代码:

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里的时候,报这个错: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.

我其它普通的js是可以的,但是百度的这个似乎不行,请问解决方法,或者其它添加js的方法(使用ajax的方法也行,只要是原生js就好了)


var loadJS = function(url, callback) {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = url;
    var done = false;
    script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            callback();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
    head.appendChild(script);
};


那是因为你页面引入的百度的js:
http://api.map.baidu.com/api?type=quick&ak=o9B4Ol99j9NcBXSu5nFTR7uI&v=1.0的内容是

javascript(function(){ 
   window.BMap_loadScriptTime = (new Date).getTime();
   document.write('<script type="text/javascript" src="http://api.map.baidu.com/getscript?type=quick&file=api&ak=o9B4Ol99j9NcBXSu5nFTR7uI&t=20140109092002">');
   document.write('</script><script type="text/javascript" src="http://api.map.baidu.com/getscript?type=quick&file=feature&ak=o9B4Ol99j9NcBXSu5nFTR7uI&t=20140109092002"></script>');
})();

里面包含了 document.write方法,异步加载的js是不允许使用document.write方法的

直接引用这两个地址的js
http://api.map.baidu.com/getscript?type=quick&file=api&ak=o9B4Ol99j9NcBXSu5nFTR7uI&t=20140109092002http://api.map.baidu.com/getscript?type=quick&file=feature&ak=o9B4Ol99j9NcBXSu5nFTR7uI&t=20140109092002就可以了


2楼正解!
错误提示已经说得很明白了:异部引入的外部文件在document中write,It isn't possible.
至于unless it is explicitly opened.怎么做,我不知道...

【热门文章】
【热门文章】