代码之家  ›  专栏  ›  技术社区  ›  B T

如何获取当前执行的javascript代码的文件路径

  •  50
  • B T  · 技术社区  · 15 年前

    我想做点像C #include "filename.c" ,或php include(dirname(__FILE__)."filename.php") 但在javascript中。我知道如果我能得到一个js文件的url(比如标签的src属性中给出的url),我就可以做到这一点。有没有办法让javascript知道这一点?

    或者,有没有什么好的方法可以从同一个域动态加载javascript(而不必特别了解该域)?例如,假设我们有两个相同的服务器(qa和production),但它们显然有不同的url域。有没有办法像这样 include("myLib.js"); mylib.js将从加载文件的域中加载到哪里?

    抱歉,如果你说的有点混乱。

    9 回复  |  直到 6 年前
        1
  •  75
  •   Yves M.    6 年前

    在脚本中:

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

    这是因为浏览器按顺序加载和执行脚本,所以当脚本执行时,它所包含的文档一定会将script元素作为页面上的最后一个元素。当然,此代码必须是脚本的“全局”代码,所以保存 src 以后可以用的地方。通过将全局变量包装为:

    (function() { ... })();
    
        2
  •  33
  •   Rudie    7 年前

    除Internet Explorer(任何版本)外的所有浏览器都具有 document.currentScript ,它总是可以正常工作(无论文件是如何包含的(async、bookmarklet等))。

    如果你想知道你现在所在的js文件的完整url:

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

    塔达亚

        3
  •  16
  •   Kevinleary.net    10 年前

    如果文档中有内联脚本,则此处接受的答案不起作用。为了避免这种情况,您可以使用以下命令 <script> 标记为 [src] 属性。

    /**
     * Current Script Path
     *
     * Get the dir path to the currently executing script file
     * which is always the last one in the scripts array with
     * an [src] attr
     */
    var currentScriptPath = function () {
    
        var scripts = document.querySelectorAll( 'script[src]' );
        var currentScript = scripts[ scripts.length - 1 ].src;
        var currentScriptChunks = currentScript.split( '/' );
        var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];
    
        return currentScript.replace( currentScriptFile, '' );
    }
    

    这有效地捕获了最后一个external.js文件,解决了我在使用内联js模板时遇到的一些问题。

        4
  •  6
  •   Alexandre Daubricourt    8 年前

    我刚做了个小把戏:

    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

    操作:chrome、firefox、edge

    享受吧!

        5
  •  5
  •   Stoutie    10 年前

    根据这里找到的答案,我得出以下结论:

    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;
    

    顺便说一句:我在用 CommonJS 模块格式和捆绑 webpack .

        6
  •  4
  •   B T    11 年前

    我最近发现了一种更干净的方法,可以随时执行,而不是在脚本加载时被迫同步执行。

    使用 stackinfo 在当前位置获取stacktrace,并获取 info.file 从栈顶起的名字。

    info = stackinfo()
    console.log('This is the url of the script '+info[0].file)
    
        7
  •  2
  •   Afonso Matos    10 年前

    我编写了一个简单的函数,它允许使用try/catch方法获取当前javascript文件的绝对位置。

    你可以看到它 here

        8
  •  1
  •   johnmdonahue    15 年前

    我可能误解了您的问题,但似乎只要生产和开发服务器使用相同的路径结构,您就应该能够使用相对路径。

    <script language="javascript" src="js/myLib.js" />
    
        9
  •  0
  •   Graza    15 年前

    不管它是一个脚本,一个html文件(例如一个框架),css文件,图片,无论什么,如果你 指定一个服务器/域HTML文档的路径将是默认的,因此您可以这样做,例如,

    <script type=text/javascript src='/dir/jsfile.js'></script>

    <script type=text/javascript src='../../scripts/jsfile.js'></script>

    如果不提供服务器/域,则路径将与页面的路径或主文档路径的脚本相关