问题
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