我的脚本源 URL 是什么? [英] What is my script src URL?

查看:36
本文介绍了我的脚本源 URL 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单可靠的方法来确定当前正在执行的 JavaScript 文件(在网页内)的 URL?

Is there a simple and reliable way to determine the URL of the currently-executing JavaScript file (inside a web page)?

我对此的唯一想法是扫描 DOM 中的所有脚本 src 属性,以查找当前文件是如何被引用的,然后通过将其应用于 document.txt 来找出绝对 URL.位置.任何人都有其他想法,是否有一些我完全忽略的超级简单方法?

My only thought on this is to scan the DOM for all the script src attributes to find how the current file was referenced and then figure out the absolute URL by applying it to document.location. Anyone have other ideas, is there some super-easy method I completely overlooked?

更新:通过 DOM 访问的脚本元素已经有一个包含完整 URL 的 src 属性.我不知道那是多么普遍/标准,但你也可以使用 getAttribute("src") 它将返回 [X]HTML 中的任何原始属性值.

UPDATE: Script elements accessed via the DOM already have a src property which contains the full URL. I don't know how ubiquitous/standard that is, but alternatively you can use getAttribute("src") which will return whatever raw attribute value is in the [X]HTML.

推荐答案

把这个放在需要知道自己url的js文件中.

Put this in the js file that needs to know it's own url.

完全合格(例如 http://www.example.com/js/main.js):

var scriptSource = (function(scripts) {
    var scripts = document.getElementsByTagName('script'),
        script = scripts[scripts.length - 1];

    if (script.getAttribute.length !== undefined) {
        return script.src
    }

    return script.getAttribute('src', -1)
}());

或者它出现在源代码中(例如 /js/main.js):

var scriptSource = (function() {
    var scripts = document.getElementsByTagName('script'),
        script = scripts[scripts.length - 1];

    if (script.getAttribute.length !== undefined) {
        return script.getAttribute('src')
    }

    return script.getAttribute('src', 2)
}());

参见 http://www.glennjones.net/Post/809/getAttributehrefbug.htm 用于解释正在使用的 getAttribute 参数(这是一个 IE 错误).

See http://www.glennjones.net/Post/809/getAttributehrefbug.htm for explanation of the getAttribute parameter being used (it's an IE bug).

这篇关于我的脚本源 URL 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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