简体   繁体   English

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

[英]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.URLwindow.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允许各种其他隐式类型转换。

  • mozilla reference : document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. mozilla引用document.location最初是一个只读属性,虽然Gecko浏览器也允许你分配它。 For cross-browser safety, use window.location instead. 对于跨浏览器安全性,请改用window.location To retrieve just the URL as a string, the read-only document.URL property can be used. 要仅将URL检索为字符串,可以使用只读document.URL属性。
  • Sun reference : Do not use location as a property of the document object; Sun参考 :不要将location用作document对象的属性; use the document.URL property instead. 请改用document.URL属性。 The 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.

相关问题 我如何在 javascript 中获取文件 url 数据 - How can i get file url data in javascript 获取 JavaScript 文件的 URL - Get URL of JavaScript File 如何使用jquery / javascript获取任何网站的html源代码,例如php的file_get_content? - How can I get a html source code of any website using jquery/javascript like php's file_get_content? JavaScript:如何获取发布到我的代码中的 json.file? - JavaScript: How can Get the json.file that it was post to my code? 如何从 javascript 中的 URL 获取 File() 或 Blob()? - How to get a File() or Blob() from an URL in javascript? 在JavaScript中,如何获取JavaScript文件的URL,而不是位置URL? - In JavaScript, how do I get the URL of the JavaScript file, not the location URL? 外部托管的javascript文件的代码能否与Page中的window.load并行执行 - Can an externally hosted javascript file's code get executed parallel with window.load in a Page Javascript文件中的代码可以知道自己的域/ URL - Can code in a Javascript file know its own domain/URL 如何使用签名的 URL 和 JavaScript 将二进制字符串文件上传到 Amazon S3? - How can I upload a file that is a binary string to Amazon S3 using a signed URL and JavaScript? javascript上传者可以更改文件的二进制代码吗? - Can javascript uploaders change file's binary code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM