How to get the file-path of the currently executing javascript code

后端 未结 10 867
南笙
南笙 2020-11-29 19:18

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

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 19:22

    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() { ... })();
    

提交回复
热议问题