可能重复: Include a JavaScript file in a JavaScript file How to include a JavaScript file in another JavaScript file?
在JavaScript函数()中导入JavaScript文件(例如file.js
)的最佳方法是什么?
例如,替换todo语句的最佳方法是什么:
function doSomething() {
if (xy.doSomething == undefined) {
// TODO: load 'oldVersionPatch.js'
}
...
}
最好的解决方案可能是创建脚本元素并将其添加到HTML页面中。
答案 0 :(得分: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);
..应该这样做
答案 1 :(得分: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);
}
}
答案 2 :(得分:1)
很简单,在JavaScript中创建一个<script>
元素,将src
属性附加到URL的任何内容并附加到DOM。应该这样做。
答案 3 :(得分:1)
你必须让你的代码异步才能获得这个:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = yourJavascriptFileLocation;
script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState === 'complete') {
/* Your code rely on this JavaScript code */
}
};
var head = document.getElementsByTagName('head')[0];
// Don't use appendChild
head.insertBefore(script, head.firstChild);