Get script path

Searching the DOM for your own <script> tag as above is the usual method, yes.

However, you usually needn’t search too hard: when you’re in the body of the script — run at include-time — you know very well which <script> element you are: the last one. The rest of them can’t have been parsed yet.

var scripts= document.getElementsByTagName('script');
var path= scripts[scripts.length-1].src.split('?')[0];      // remove any ?query
var mydir= path.split("https://stackoverflow.com/").slice(0, -1).join("https://stackoverflow.com/")+"https://stackoverflow.com/";  // remove last filename part of path

function doSomething() {
    img.src= mydir+'../images/myimage.jpeg';
}

This doesn’t hold true if your script has been linked with <script defer> (or, in HTML5, <script async>). However, this is currently rarely used.

Leave a Comment