在JavaScript函数中导入JavaScript文件

Mat*_*mes 16 javascript

可能重复: 在JavaScript文件中包含JavaScript文件 如何在另一个JavaScript文件中包含JavaScript文件?

导入JavaScript文件的最佳方法是什么,例如file.js,在JavaScript函数()中?

例如,替换todo语句的最佳方法是什么:

function doSomething() {
   if (xy.doSomething == undefined) {
      // TODO: load 'oldVersionPatch.js'
   }
   ...
}
Run Code Online (Sandbox Code Playgroud)

可能最好的解决方案是创建脚本元素并将其添加到HTML页面中.

  • 是否更好地将它添加/添加到头部或身体(什么时候会加载)?
  • 使用JavaScript或jQuery(什么是跨浏览器兼容)更好?

Att*_*cus 5

  var filename = 'oldVersionPatch.js';
  var js = document.createElement('script');
  js.setAttribute("type","text/javascript");
  js.setAttribute("src", filename);
  document.getElementsByTagName("head")[0].appendChild(js);
Run Code Online (Sandbox Code Playgroud)

..应该这样做


小智 5

http://api.jquery.com/jQuery.getScript/

要么

(function(){
  this.__defineGetter__("__FILE__", function() {
    return (new Error).stack.split("\n")[2].split("@")[1].split(":").slice(0,-1).join(":");
  });
})();

(function(){
  this.__defineGetter__("__DIR__", function() {
    return __FILE__.substring(0, __FILE__.lastIndexOf('/'));
  });
})();

function include(file,charset) {
    if (document.createElement && document.getElementsByTagName) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', __DIR__ + '/' + file);
        if(charset){
            script.setAttribute('charset', charset);
        }
        head.appendChild(script);
    }
}
Run Code Online (Sandbox Code Playgroud)