Import JavaScript file in JavaScript function
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicates:
Include a JavaScript file in a JavaScript file
How to include a JavaScript file in another JavaScript file?
在javascript函数()中导入javascript文件(例如
例如,替换TODO语句的最佳方法是:
1 2 3 4 5 6 | function doSomething() { if (xy.doSomething == undefined) { // TODO: load 'oldVersionPatch.js' } ... } |
最好的解决方案可能是创建脚本元素并将其添加到HTML页面中。
- 在头部或主体中添加/附加它更好吗(什么时候加载)?
- 使用javascript或jquery更好吗(什么是更兼容的跨浏览器)?
http://api.jquery.com/jquery.getscript/
或
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | (function(){ this.__defineGetter__("__FILE__", function() { return (new Error).stack.split(" ")[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); } } |
1 2 3 4 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 2 3 4 5 6 7 8 9 10 11 | 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); |
很简单,在javascript中创建一个