Javascript: how can I find out where .js is located?

I am writing a small javascript library, it uses an image. I want to create a directory structure as follows:

  / lib
    / mylib
       main.js
       / img
           main.png
    / other libraries ...
 index.html

But if I hardcode the image path lib/mylib/img/main.png , my library cannot be used in another directory structure.

I want to use the "relative path", which is relative to main.js. itself. So that I can write path + 'img/main.png' to access the image.

How can I find out where main.js is?

0
source share
1 answer

You can extract it from the <script> :

 function getScriptPath() { var scriptTags = document.getElementsByTagName('script'); return scriptTags[scriptTags.length - 1].src.split('?')[0].split('/').slice(0, -1).join('/') + '/'; } 
+1
source