Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - Get script path

In CSS, any image path is relative to the CSS file location.

f.ex if I put the CSS file in /media/css/mystyles.css and use something like

.background:url(../images/myimage.jpg);

The browser will look for the image in /media/images/myimage.jpg which makes sense.

Is it possible to do the same thing in javascript?

F.ex if I include /media/js/myscript.js and put this code in there:

var img = new Image();
img.src = '../images/myimage.jpg';

Th image is not found, since browser is using the HTML file as a starting point, instead of the script location. I would like to be able to use the script location as a starting point, just like CSS does. Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('/').slice(0, -1).join('/')+'/';  // 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...