我需要加载跨域JavaScript
动态文件为我的网站http://jsbookmarklets.com/中的bookmarklet
解决方案应满足:
>获取当前文件的路径
>当前网页的域和执行中的JS文件是不同的
>解决方案应该是跨浏览器
>可以异步加载多个脚本(这就是下面提到的相关问题不合适的原因)
我想获取当前正在执行的JavaScript代码的文件路径,以便动态加载更多资源(更多CSS文件和JS文件,如自定义代码和jQuery,jQuery UI和Ext JS库),这些文件存储在与JavaScript相同/相对的文件夹中小书签.
以下方法不适合我的问题:
var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length-1].src;
alert("THIS IS: "+src);
相关问题不符合我的问题:
> Get the url of currently executing js file when dynamically loaded
> Get script path
最佳答案
我正在使用的当前解决方案,但有效但非常冗长:
原文链接:https://www.f2er.com/jquery/428150.htmlvar fnFullFilePathToFileParentPath = function(JSFullFilePath){
var JSFileParentPath = '';
if(JSFullFilePath) {
JSFileParentPath = JSFullFilePath.substring(0,JSFullFilePath.lastIndexOf('/')+1);
} else {
JSFileParentPath = null;
}
return JSFileParentPath;
};
var fnExceptionToFullFilePath = function(e){
var JSFullFilePath = '';
if(e.fileName) { // firefox
JSFullFilePath = e.fileName;
} else if (e.stacktrace) { // opera
var tempStackTrace = e.stacktrace;
tempStackTrace = tempStackTrace.substr(tempStackTrace.indexOf('http'));
tempStackTrace = tempStackTrace.substr(0,tempStackTrace.indexOf('Dummy Exception'));
tempStackTrace = tempStackTrace.substr(0,tempStackTrace.lastIndexOf(':'));
JSFullFilePath = tempStackTrace;
} else if (e.stack) { // firefox,opera,chrome
(function(){
var str = e.stack;
var tempStr = str;
var strProtocolSeparator = '://';
var idxProtocolSeparator = tempStr.indexOf(strProtocolSeparator)+strProtocolSeparator.length;
var tempStr = tempStr.substr(idxProtocolSeparator);
if(tempStr.charAt(0)=='/') {
tempStr = tempStr.substr(1);
idxProtocolSeparator++;
}
var idxHostSeparator = tempStr.indexOf('/');
tempStr = tempStr.substr(tempStr.indexOf('/'));
var idxFileNameEndSeparator = tempStr.indexOf(':');
var finalStr = (str.substr(0,idxProtocolSeparator + idxHostSeparator + idxFileNameEndSeparator));
finalStr = finalStr.substr(finalStr.indexOf('http'));
JSFullFilePath = finalStr;
}());
} else { // internet explorer
JSFullFilePath = null;
}
return JSFullFilePath;
};
var fnExceptionToFileParentPath = function(e){
return fnFullFilePathToFileParentPath(fnExceptionToFullFilePath(e));
};
var fnGetJSFileParentPath = function() {
try {
throw new Error('Dummy Exception');
} catch (e) {
return fnExceptionToFileParentPath(e);
}
};
var JSFileParentPath = fnGetJSFileParentPath();
alert('File parent path: ' + JSFileParentPath);