[removed] how can I know where is the .js self?

2019-09-04 12:28发布

问题:

I write a small javascript library, it use a image. I want to build the directory structure like this:

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

But if I hard-code the image path lib/mylib/img/main.png, my library can't be used in other directory structure.

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

How can I know where is the main.js?

回答1:

You can extract it from your <script> tag:

function getScriptPath() {
  var scriptTags = document.getElementsByTagName('script');

  return scriptTags[scriptTags.length - 1].src.split('?')[0].split('/').slice(0, -1).join('/') + '/';
}