我编写了一个类来查找与延迟加载和异步脚本标记一起使用的脚本的路径。
我有一些相对于我的脚本的模板文件,因此,我没有对它们进行硬编码,而是创建了创建类来自动创建路径。完整的源代码在github上。
不久前,我使用arguments.callee尝试执行类似的操作,但最近我在MDN上阅读到,严格模式下不允许使用。
function ScriptPath() {
var scriptPath = '';
try {
throw new Error();
}
catch(e) {
var stackLines = e.stack.split('\n');
var callerIndex = 0;
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
callerIndex = Number(i) + 2;
break;
}
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}