开发者

javascript: how can I know where is the .js self?

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?


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('/') + '/';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜