[英]How can code in a JavaScript file get the file's URL?
I need to dynamically load a CSS stylesheet into a page that's on a different domain. 我需要动态地将CSS样式表加载到不同域中的页面。 How can I get the complete URL of the JS file to use in the href attribute of the stylesheet?
如何获取要在样式表的href属性中使用的JS文件的完整URL?
For instance, here is the structure: 例如,这是结构:
http://bla.com/js/script.js
http://bla.com/css/style.css
I want to dynamically load the stylesheet into a page http://boo.net/index.html . 我想动态地将样式表加载到页面http://boo.net/index.html中 。 The problem is, I don't know the bla.com bit in advance, just the fact that the stylesheet is in ../css/ relative to the JS file.
问题是,我事先并不知道bla.com位,只是样式表在../css/中相对于JS文件。
The script is, of course, included on index.html . 当然,该脚本包含在index.html中 。 jQuery's fine too.
jQuery也很好。
Add an ID to the script tag: 在脚本标记中添加ID:
<script type="text/javascript" id="myScript" src="http://bla.com/js/script.js"></script>
And in http://bla.com/js/script.js
: 在
http://bla.com/js/script.js
:
var myScript = document.getElementById('myscript');
var myScriptSrc = myScript.getAttribute('src');
alert(myScriptSrc); // included for debugging
You should be able to manipulate the value of myScriptSrc
to obtain the path to any other content on bla.com
. 你应该能够操纵的价值
myScriptSrc
来获取其他任何内容的路径bla.com
。
I think this sample is what James Black meant in his answer. 我认为这个样本是James Black在他的回答中的意思。
Lastly, to everyone suggesting the use of document.location
, please keep in mind that if you want read-only access to the current page address, you should be using document.URL
or window.location
. 最后,对于每个人建议使用
document.location
,请记住,如果您想要只读访问当前页面地址,您应该使用document.URL
或window.location
。 If you want to set the page address, you should always use window.location.href
. 如果要设置页面地址,则应始终使用
window.location.href
。 Although window.location = 'location';
虽然
window.location = 'location';
works, it has always bothered me to see a String being assigned to a Location. 工作,它总是困扰我看到一个字符串被分配到一个位置。 I'm not sure why since JavaScript allows all sorts of other implicit type conversions.
我不确定为什么因为JavaScript允许各种其他隐式类型转换。
document.location
was originally a read-only property, although Gecko browsers allow you to assign to it as well. document.location
最初是一个只读属性,虽然Gecko浏览器也允许你分配它。 For cross-browser safety, use window.location instead. document
object; document
对象的属性; use the document.URL property instead. document.location
property, which is a synonym for document.URL
, is deprecated. document.location
属性,它是document.URL
的同义词。 Even easier than using an id
is to just leave the markup alone and use document.currentScript
. 比使用
id
更简单的方法就是单独留下标记并使用document.currentScript
。 The link to MDN mentions under the Notes section, a small quirk requiring the JavaScript to execute synchronously, and I'm about to explain how to avoid this pitfall. MDN的链接在Notes部分提到,一个小怪癖需要JavaScript同步执行,我即将解释如何避免这个陷阱。
It's important to note that this will not reference the
<script>
element if the code in the script is being called as a callback or event handler;重要的是要注意,如果
<script>
的代码被调用为回调或事件处理程序,则不会引用<script>
元素; it will only reference the element while it's initially being processed.它只会在最初处理时引用该元素。
The advantage of this solution is that you are not required to use special markup, and this is especially helpful if you can't access the HTML yourself for some reason (eg if it's used by a client or a developer using your API). 此解决方案的优点是您不需要使用特殊标记,如果您由于某种原因无法自己访问HTML(例如,如果客户端或开发人员使用您的API使用它),这将特别有用。
If the script is executed synchronously (meaning the main content of the script isn't wrapped in an event listener or some other function set to evaluate later than when the code is "initially being processed" ), you can simply use document.currentScript
to access the currently processing <script>
element of your code. 如果脚本是同步执行的(意味着脚本的主要内容没有包含在事件监听器或其他一些函数集中,以便在代码“最初处理”之后进行评估),您只需使用
document.currentScript
即可访问代码的当前处理<script>
元素。 To demonstrate how to use this effectively, I'll provide a basic demo below. 为了演示如何有效地使用它,我将在下面提供一个基本演示。
HTML: HTML:
<script type="text/javascript" src="http://bla.com/js/script.js"></script>
JavaScript in http://bla.com/js/script.js
: http://bla.com/js/script.js
JavaScript:
var myScript = document.currentScript,
mySrc = myScript.getAttribute('src');
console.log(mySrc); // "http://bla.com/js/script.js"
$(function () {
// your other code here, assuming you use jQuery
// ...
});
If you don't want the variable to be exposed to the global scope, you can also do this: 如果您不希望将变量公开给全局范围,您也可以这样做:
(function () {
var myScript = document.currentScript,
mySrc = myScript.getAttribute('src');
console.log(mySrc); // "http://bla.com/js/script.js"
$(function () {
// your other code here
// ...
});
}()); // self-executing anonymous function
Basically the point is to make sure and access document.currentScript
during synchronous execution of the script, otherwise it will not reference what you expect it to. 基本上,重点是在脚本的同步执行期间确保并访问
document.currentScript
,否则它将不会引用您期望的内容。
With Jquery, you could do something like: 使用Jquery,您可以执行以下操作:
$('script[src$="my_script.js"]').attr('src').replace('my_script.js','');
// outputs something like: "/static/js/"
var JS_SELF_URL = (function() {
var script_tags = document.getElementsByTagName('script');
return script_tags[script_tags.length-1].src;
})();
As the browser parses tags, it also downloads and executes them. 当浏览器解析标签时,它还会下载并执行它们。 Therefore when your JS file is executed it is currently the last tag parsed.
因此,当您执行JS文件时,它是当前解析的最后一个标记。
您可以阅读document.location
,但您也可以使用相对URL
您可以在脚本标记中查找javascript位置,并且通过使用document.location,您可以确定相对寻址,以确定css文件的位置。
Stack property of error objects can provide URL information. 错误对象的堆栈属性可以提供URL信息。
try
{
throw new Error();
}
catch(exc)
{
console.log(exc.stack);
}
Unfortunately, Webkit doesn't (but Chromium does) support stack property. 不幸的是,Webkit没有(但Chromium确实)支持堆栈属性。 There are a few browsers supporting this feature: http://173.45.237.168/reference/html/api/Error.html#Error.stack
有一些浏览器支持此功能: http : //173.45.237.168/reference/html/api/Error.html#Error.stack
Instead of stack, Webkit provides sourceURL property, here is the exampe usage: Webkit提供了sourceURL属性,而不是堆栈,这里是示例用法:
try
{
throw new Error();
}
catch(exc)
{
console.log(exc.sourceURL);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.