Get script path

前端 未结 13 1246
青春惊慌失措
青春惊慌失措 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:35

    I wrote a class to find get the path of scripts that works with delayed loading and async script tags. It's based on inspecting the stack trace and there are a couple of functions to format the results but it's intended to be basic. If nothing else use it as a reference.

    function ScriptPath() {
      var scriptPath = '';
      try {
        //Throw an error to generate a stack trace
        throw new Error();
      }
      catch(e) {
        //Split the stack trace into each line
        var stackLines = e.stack.split('\n');
        var callerIndex = 0;
        //Now walk though each line until we find a path reference
        for(var i in stackLines){
          if(!stackLines[i].match(/http[s]?:\/\//)) continue;
          //We skipped all the lines with out an http so we now have a script reference
          //This one is the class constructor, the next is the getScriptPath() call
          //The one after that is the user code requesting the path info (so offset by 2)
          callerIndex = Number(i) + 2;
          break;
        }
        //Now parse the string for each section we want to return
        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('.');
      };
    }
    

    Full source

    0 讨论(0)
  • 2020-11-30 01:39

    For asynchronous scripts, script tag walking won't do. So if: - performance.timing exists (like in new non-Safari browsers) & You have not reached its max, or have pushed-up its max before loading & Your script was the most recent thing loaded:

    performance.getEntries().slice(-1)[0].name 
    

    To push-up the max, do something like this:

    performance.webkitSetResourceTimingBufferSize(10000)
    
    0 讨论(0)
  • 2020-11-30 01:44

    (If base [Rubens's answer] doesn't work for you. Edit: Apparently he removed it, but I thought it was relevant; see base on the W3C site.)

    It's possible, but it's a pain. :-) You have to search the DOM for the script tag that imported your script, and then grab its src value. That's how script.aculo.us does its module auto-loading; you can refer to the scriptaculous.js file for an example.

    0 讨论(0)
  • 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;i<sclist.length&&!found;i++){
            // check if tag have source (avoid local scripts tags)
            if(typeof(sclist[i].src)=="string"){
                // remove arguments and extract file basename
                var file = sclist[i].src.split("?")[0].split("/").pop();
                // get path if found
                if(file==scriptFileName)found = sclist[i].src.split("?")[0];
            }
        }
        // compare with document location
        if(found){
            var _from = document.location.href.split("/");
            var _to__ = found.split("/");
            // remove files names
            _from.pop();_to__.pop();
            // remove common pathes
            while(_from.length>0&&_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);
    
    0 讨论(0)
  • 2020-11-30 01:46

    In my case it isn't scripts.length-1.
    Example:
    In debug mode js file location: //server/js/app.js
    In prod mode js file location: //server/js-build/app.js
    The file name is known; the single way to find path by it's name:

    getExecutionLocationFolder() {
        var fileName = "app.js";
        var scriptList = $("script[src]");
        var jsFileObject = $.grep(scriptList, function(el) {
            var currentElement = el.src.contains(fileName);
            return currentElement;
        });
        var jsFilePath = jsFileObject[0].src;
        var jsFileDirectory = jsFilePath.substring(0, jsFilePath.lastIndexOf("/") + 1);
        return jsFileDirectory;
    };
    
    0 讨论(0)
  • 2020-11-30 01:47

    One line "Pathfinder", when you know your script file name (here include.js):

    // Script file name
    var file = 'include.js';
    
    // jQuery version
    var path = (src = jQuery('script[src$="' + file + '"]').attr('src')).substring(0, src.lastIndexOf("/") + 1);
    // jQuery with error handling
    var path = (src = jQuery('script[src$="' + file + '"]').attr('src') ? src : 'Path/Not/Found/').substring(0, src.lastIndexOf("/") + 1);
    
    // Plain JS version
    var path = (src = document.querySelector('script[src$="' + file + '"]').src).substring(0, src.lastIndexOf("/") + 1);
    // Plain JS with error handling
    var path = (src = (script = document.querySelector('script[src$="' + file + '"]')) ? script.src : 'Path/Not/Found/').substring(0, src.lastIndexOf("/") + 1);
    
    0 讨论(0)
提交回复
热议问题