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?
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.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.