JavaScript文件中的代码如何获取文件的URL?

mon*_*ist 14 javascript jquery path cross-domain

我需要动态地将CSS样式表加载到不同域中的页面.如何获取要在样式表的href属性中使用的JS文件的完整URL ?

例如,这是结构:

http://bla.com/js/script.js

http://bla.com/css/style.css

我想动态地将样式表加载到页面http://boo.net/index.html中.问题是,我事先并不知道bla.com位,只是样式表在../css/中相对于JS文件.

当然,该脚本包含在index.html中.jQuery也很好.

Gra*_*ner 15

在脚本标记中添加ID:

<script type="text/javascript" id="myScript" src="http://bla.com/js/script.js"></script>
Run Code Online (Sandbox Code Playgroud)

并在http://bla.com/js/script.js:

var myScript = document.getElementById('myscript');
var myScriptSrc = myScript.getAttribute('src');
alert(myScriptSrc); // included for debugging
Run Code Online (Sandbox Code Playgroud)

您应该能够操纵值myScriptSrc以获取任何其他内容的路径bla.com.

我认为这个样本是James Black在他的回答中的意思.

最后,对于每个人建议使用document.location,请记住,如果您想要只读访问当前页面地址,您应该使用document.URLwindow.location.如果要设置页面地址,则应始终使用window.location.href.虽然window.location = 'location';有效,但我一直困扰着看到一个字符串被分配到一个位置.我不确定为什么因为JavaScript允许各种其他隐式类型转换.

  • mozilla reference:document.location最初是一个只读属性,虽然Gecko浏览器也允许你分配它.对于跨浏览器安全性,请改用window.location.要仅将URL检索为字符串,可以使用只读document.URL属性.
  • Sun参考:不要将location用作document对象的属性; 请改用document.URL属性.该document.location属性是其同义词document.URL,已弃用.


Pat*_*rts 11

比使用a更容易id就是单独留下标记并使用document.currentScript.MDN的链接在Notes部分提到,一个小怪癖需要JavaScript同步执行,我即将解释如何避免这个陷阱.

重要的是要注意,<script>如果脚本中的代码被调用为回调或事件处理程序,则不会引用该元素; 它只会在最初处理时引用该元素.

此解决方案的优点是您不需要使用特殊标记,如果您由于某种原因无法自己访问HTML(例如,如果客户端或开发人员使用您的API使用它),这将特别有用.

如果脚本是同步执行的(意味着脚本的主要内容没有包含在事件监听器中,或者某些其他功能集要在代码"最初处理"之后进行评估),您只需使用document.currentScript访问当前处理<script>代码的元素.为了演示如何有效地使用它,我将在下面提供一个基本演示.

HTML:

<script type="text/javascript" src="http://bla.com/js/script.js"></script>
Run Code Online (Sandbox Code Playgroud)

JavaScript中http://bla.com/js/script.js:

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
    // ...
});
Run Code Online (Sandbox Code Playgroud)

如果您不希望将变量公开给全局范围,您也可以这样做:

(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
Run Code Online (Sandbox Code Playgroud)

基本上,重点是document.currentScript在脚本的同步执行期间确保和访问,否则它将不会引用您期望的内容.

  • 这个答案值得更多的选票! (3认同)

小智 7

使用Jquery,您可以执行以下操作:

$('script[src$="my_script.js"]').attr('src').replace('my_script.js','');
// outputs something like: "/static/js/"
Run Code Online (Sandbox Code Playgroud)


bra*_*adt 6

var JS_SELF_URL = (function() {
    var script_tags = document.getElementsByTagName('script');
    return script_tags[script_tags.length-1].src;
})();
Run Code Online (Sandbox Code Playgroud)

当浏览器解析标签时,它也会下载并执行它们。因此,当您的 JS 文件被执行时,它是当前解析的最后一个标签。

  • 使用 `async` 关键字时避免这种情况。 (2认同)