动态加载JS内部的JS
这个问题在这里已经有了答案:
  jQuery的$.getScript()有时是bug,所以我使用我自己的实现: 
jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}
并像这样使用它:
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});
我的猜测是,在你的DOM-only解决方案中,你做了如下的事情:
var script = document.createElement('script');
script.src = something;
//do stuff with the script
首先,这是行不通的,因为脚本没有添加到文档树中,所以它不会被加载。 此外,即使你这样做了,在另一个脚本加载的时候JavaScript的执行仍然继续,所以在完全加载脚本之前,它的内容将不可用。
  您可以听取脚本的load事件,并按照您的结果处理结果。  所以: 
var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;
document.head.appendChild(script); //or something of the likes
我需要经常这样做,所以我使用这个:
var loadJS = function(url, implementationCode, location){
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to 
    //insert the <script> element
    var scriptTag = document.createElement('script');
    scriptTag.src = url;
    scriptTag.onload = implementationCode;
    scriptTag.onreadystatechange = implementationCode;
    location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);
有关更多信息,请参阅本网站如何在另一个JavaScript文件中包含JavaScript文件?这是我的功能构想的来源。
链接地址: http://www.djcxy.com/p/42471.html