获取脚本路径 [英] Get script path

查看:109
本文介绍了获取脚本路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CSS中,任何图片路径都是相对于CSS文件位置。



f.ex如果我将CSS文件放在 / media /css/mystyles.css 并使用类似

  .background:url /myimage.jpg); 

浏览器将在 / media / images / myimage中查找图像。



可以在javascript中执行同样的操作吗? b
$ b

F.ex如果我包括 /media/js/myscript.js 并将此代码放在那里:

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

找不到Th图片,因为浏览器使用HTML文件作为起点,而不是脚本位置。我想能够使用脚本位置作为起点,就像CSS一样。 这是否可能?

解决方案

搜索DOM自己的



但是,你通常不需要太难搜索:当你在脚本的主体 - 在include-time运行 - 你知道哪个< script> 元素你是:最后一个。其他人还不能解析。

  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';
}

如果您的脚本已链接到< script defer> (或在HTML5中,< script async> )。但是,目前很少使用。


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.

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.

这篇关于获取脚本路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆