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

痞子三分冷 提交于 2019-12-13 05:14:39

问题


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


来源:https://stackoverflow.com/questions/6273654/javascript-how-can-i-know-where-is-the-js-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!