How to get the file-path of the currently executin

2019-01-13 01:23发布

I'm trying to do something like a C #include "filename.c", or PHP include(dirname(__FILE__)."filename.php") but in javascript. I know I can do this if I can get the URL a js file was loaded from (e.g. the URL given in the src attribute of the tag). Is there any way for the javascript to know that?

Alternatively, is there any good way to load javascript dynamically from the same domain (without knowing the domain specifically)? For example, lets say we have two identical servers (QA and production) but they clearly have different URL domains. Is there a way to do something like include("myLib.js"); where myLib.js will load from the domain of the file loading it?

Sorry if thats worded a little confusingly.

9条回答
Luminary・发光体
2楼-- · 2019-01-13 01:51

I just made this little trick :

window.getRunningScript = () => {
    return () => {
        let err = new Error()
        let link = err.stack.split('(')
        link = link[1]
        link = link.split(')')[0]
        link = link.split(':')
        link.splice(-2, 2)
        link = link.join(':')

        return link
    }
}

console.log('%c Currently running script:', 'color: blue', getRunningScript()())

screenshot

Work on: Chrome, Firefox, Edge

enjoy !

查看更多
SAY GOODBYE
3楼-- · 2019-01-13 01:52

Refining upon the answers found here I came up with the following:

getCurrentScript.js

var getCurrentScript = function () {
  if (document.currentScript) {
    return document.currentScript.src;
  } else {
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length-1].src;

  }
};

module.exports = getCurrentScript;

getCurrentScriptPath.js

var getCurrentScript = require('./getCurrentScript');

var getCurrentScriptPath = function () {
  var script = getCurrentScript();
  var path = script.substring(0, script.lastIndexOf('/'));
  return path;
};

module.exports = getCurrentScriptPath;

BTW: I'm using CommonJS module format and bundling with webpack.

查看更多
冷血范
4楼-- · 2019-01-13 01:54

All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).

If you want to know the full URL of the JS file you're in right now:

var script = document.currentScript;
var fullUrl = script.src;

Tadaa.

查看更多
Deceive 欺骗
5楼-- · 2019-01-13 01:56

Within the script:

var scripts = document.getElementsByTagName("script"),
    src = scripts[scripts.length-1].src;

This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

(function() { ... })();
查看更多
干净又极端
6楼-- · 2019-01-13 01:56

I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.

Use stackinfo to get a stacktrace at a current location, and grab the info.file name off the top of the stack.

info = stackinfo()
console.log('This is the url of the script '+info[0].file)
查看更多
够拽才男人
7楼-- · 2019-01-13 02:04

I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.

<script language="javascript" src="js/myLib.js" />
查看更多
登录 后发表回答