获取当前js文件的绝对路径的方法

时间:2024-03-08 13:00:20
var strJsPath=\'\';
(function(){
    try {
        throw Error("获取JS路径有误");
    }catch(ex){
        if(ex.fileName)//Firefox
            strJsPath=ex.fileName
        else if(ex.stack)//Chrome
            strJsPath=(ex.stack.match(/at\s+(.*?):\d+:\d+/)||[\'\',\'\'])[1];
        else if(ex.sourceURL)//Safari
            strJsPath=ex.sourceURL
    }
    if(strJsPath)return; //其实所有浏览器都可以用下面的
    var scripts=document.getElementsByTagName_r("script"),script=scripts[scripts.length-1];
    strJsPath=document.querySelector?script.src:script.getAttribute("src",4)//IE8直接.src
})()
alert(strJsPath);