Get script path

前端 未结 13 1725
青春惊慌失措
青春惊慌失措 2020-11-30 01:21

In CSS, any image path is relative to the CSS file location.

f.ex if I put the CSS file in /media/css/mystyles.css and use something like



        
13条回答
  •  囚心锁ツ
    2020-11-30 01:45

    you can retrieve script path by parsing document tags and compare it with the document location.

    // get relative document path to script folder
    var pathToScript=function(scriptFileName){
        // scan document to get script location
        var sclist = document.getElementsByTagName("script");
        var found = null;
        for(var i=0;i0&&_to__.length>0&&_from[0]==_to__[0]){
                _from.shift();_to__.shift();
            }
            // add parent dir offset if any
            while(_from.length>0){
                _to__.unshift("..");_from.pop();
            }
            // return relative document path to script folder
            return _to__.length>0?(_to__.join("/")+"/"):"";
        }else{
            throw("\npathToScript Error :\nscript source '"+scriptFileName+"' not found in document.");
        }
    };
    
    // use in script file "myscript.js" :
    var pathToMe = pathToScript("myscript.js");
    console.log("my dir : "+pathToMe);
    

提交回复
热议问题