我的脚本 src URL 是什么?

发布于 2024-07-25 05:42:06 字数 340 浏览 7 评论 0原文

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

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

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

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

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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

说谎友 2024-08-01 05:42:06

把它放在需要知道它自己的url的js文件中。

完全合格(例如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 错误)。

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

Fully Qualified (eg 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)
}());

Or
As it appears in source (eg /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)
}());

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

池予 2024-08-01 05:42:06

对于最新的浏览器,您可以使用 document.currentScript 来获取此信息。

var mySource = document.currentScript.src;

好处是对于异步加载的脚本来说更可靠。 据我所知,缺点是它没有得到普遍支持。 它应该在 Chrome >= 29、FireFox >= 4、Opera >= 16 上运行。像许多有用的东西一样,它似乎在 IE 中不起作用。

当我需要获取脚本路径时,我检查是否定义了 document.currentScript ,如果没有,则使用接受的答案中描述的方法。

if (document.currentScript) {
    mySource = document.currentScript.src;
} else {
    // code omitted for brevity
}

https://developer.mozilla.org/en-US/docs /Web/API/document.currentScript

For recent browsers, you can use document.currentScript to get this information.

var mySource = document.currentScript.src;

The upside is that it's more reliable for scripts that are loaded asynchronously. The downside is that it's not, as best I know, universally supported. It should work on Chrome >= 29, FireFox >= 4, Opera >= 16. Like many useful things, it doesn't seem to work in IE.

When I need to get a script path, I check to see if document.currentScript is defined, and, if not, use the method described in the accepted answer.

if (document.currentScript) {
    mySource = document.currentScript.src;
} else {
    // code omitted for brevity
}

https://developer.mozilla.org/en-US/docs/Web/API/document.currentScript

So要识趣 2024-08-01 05:42:06

如源代码中所示(例如 /js/main.js),这是跨浏览器

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

    //No need to perform the same test we do for the Fully Qualified
    return script.getAttribute('src', 2); //this works in all browser even in FF/Chrome/Safari
}()); 

完全限定 >(例如http://www.example.com/js/main.js):

经过一些测试,似乎很难在交叉中获得完全合格的浏览器方式。 Crescent Fresh 建议的解决方案 在 IE8 中无法获得完全合格的,即使它适用于 IE7

As it appears in source (e.g. /js/main.js), this is cross-browser:

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

    //No need to perform the same test we do for the Fully Qualified
    return script.getAttribute('src', 2); //this works in all browser even in FF/Chrome/Safari
}()); 

Fully Qualified (e.g. http://www.example.com/js/main.js):

After some tests it seems hard to get the fully qualified one in a cross-browser way. The solution suggested by Crescent Fresh does not work in IE8 to get the fully qualified, even if it works in IE7

唯憾梦倾城 2024-08-01 05:42:06

此方法适用于延迟、异步和延迟加载
因为您知道脚本的文件名,并且它是否是唯一的

/* see  
 * http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656
 * http://www.glennjones.net/Post/809/getAttributehrefbug.htm
 * 
 * iterate all script to find script with right filename
 * this work with async and defer (but your script MUST have a unique filemane)
 * mozilla support document.currentScript and we use it, if is set
 *
 * this will not work with local script loaded by jQuery.getScript(),
 * since there is no script tag added into the dom. the script is only evaluated in global space.
 * http://api.jquery.com/jQuery.getScript/
 *  
 * to fix this odd, you can add a reference in meta ( meta[name=srcipt][content=url] )
 * when you load the script
 */
var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename 
var scriptUrl = (function() {
    if (document.currentScript) { // support defer & async (mozilla only)
        return document.currentScript.src;
    } else {
        var ls,s;
        var getSrc = function (ls, attr) {
            var i, l = ls.length, nf, s;
            for (i = 0; i < l; i++) {
                s = null;
                if (ls[i].getAttribute.length !== undefined) { 
                    s = ls[i].getAttribute(attr, 2);                    
                }               
                if (!s) continue; // tag with no src
                nf = s;
                nf = nf.split('?')[0].split('/').pop(); // get script filename
                if (nf === scriptFilename) {
                    return s;
                }
            }
        };          
        ls = document.getElementsByTagName('script');
        s = getSrc(ls, 'src');
        if ( !s ) { // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url]
            ls = document.getElementsByTagName('meta');             
            s = getSrc(ls, 'content');
        }           
        if ( s ) return s;
    }
    return '';
})();

var scriptPath =  scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/";

jquery 插件模板:
https://github.com/mkdgs/mkdgs -snippet/blob/master/javascript/jquery.plugins.template.js

注意:这不适用于 jQuery.getScript() 加载的本地脚本,因为没有将脚本标记添加到 dom 中。 该脚本仅在全局空间中进行评估。
http://api.jquery.com/jQuery.getScript/

修复它,你可以这样做就像是:

function loadScript(url,callback) {     

    if ( $('[src="'+url+'"]').length ) return true; // is already loaded    

    // make a reference of the loaded script
    if ( $('meta[content="'+url+'"]', $("head")).length ) return true; // is already loaded 
    var meta = document.createElement('meta');
    meta.content = url;
    meta.name = 'script';
    $("head").append(meta);

    return $.ajax({
          cache: true,
          url: u,
          dataType: 'script',
          async: false,
          success : function (script) {                     
                try { 
                    if ( typeof callback == 'function' ) callback();    
                } catch (error) { 
                    //console.log(error);
                }
          }
     });
}

This method work with defer, async and lazy loading
Since you know the filename of your script, and if it will be unique

/* see  
 * http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656
 * http://www.glennjones.net/Post/809/getAttributehrefbug.htm
 * 
 * iterate all script to find script with right filename
 * this work with async and defer (but your script MUST have a unique filemane)
 * mozilla support document.currentScript and we use it, if is set
 *
 * this will not work with local script loaded by jQuery.getScript(),
 * since there is no script tag added into the dom. the script is only evaluated in global space.
 * http://api.jquery.com/jQuery.getScript/
 *  
 * to fix this odd, you can add a reference in meta ( meta[name=srcipt][content=url] )
 * when you load the script
 */
var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename 
var scriptUrl = (function() {
    if (document.currentScript) { // support defer & async (mozilla only)
        return document.currentScript.src;
    } else {
        var ls,s;
        var getSrc = function (ls, attr) {
            var i, l = ls.length, nf, s;
            for (i = 0; i < l; i++) {
                s = null;
                if (ls[i].getAttribute.length !== undefined) { 
                    s = ls[i].getAttribute(attr, 2);                    
                }               
                if (!s) continue; // tag with no src
                nf = s;
                nf = nf.split('?')[0].split('/').pop(); // get script filename
                if (nf === scriptFilename) {
                    return s;
                }
            }
        };          
        ls = document.getElementsByTagName('script');
        s = getSrc(ls, 'src');
        if ( !s ) { // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url]
            ls = document.getElementsByTagName('meta');             
            s = getSrc(ls, 'content');
        }           
        if ( s ) return s;
    }
    return '';
})();

var scriptPath =  scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/";

a jquery plugin template with it:
https://github.com/mkdgs/mkdgs-snippet/blob/master/javascript/jquery.plugins.template.js

note: this will not work with local script loaded by jQuery.getScript(), since there is no script tag added into the dom. the script is only evaluated in global space.
http://api.jquery.com/jQuery.getScript/

to fix it you can do something like:

function loadScript(url,callback) {     

    if ( $('[src="'+url+'"]').length ) return true; // is already loaded    

    // make a reference of the loaded script
    if ( $('meta[content="'+url+'"]', $("head")).length ) return true; // is already loaded 
    var meta = document.createElement('meta');
    meta.content = url;
    meta.name = 'script';
    $("head").append(meta);

    return $.ajax({
          cache: true,
          url: u,
          dataType: 'script',
          async: false,
          success : function (script) {                     
                try { 
                    if ( typeof callback == 'function' ) callback();    
                } catch (error) { 
                    //console.log(error);
                }
          }
     });
}
ヤ经典坏疍 2024-08-01 05:42:06

如果这是一个严格的客户端解决方案,那么您的解决方案听起来不错。

如果您在服务器上编写代码,您可能只需使用脚本的完全解析 URL 填充 div/隐藏字段/(在此处插入您最喜欢的 HTML 元素),然后使用客户端的 javascript 获取该内容。

If this is a strictly client solution, yours sounds pretty good.

If you are writing code on the server, you could probably just populate a div/hidden field/(insert your fave HTML element here) with the fully resolved URL to the script, and pick that up with your javascript on the clientside.

像极了他 2024-08-01 05:42:06

您可能想查看 https://addons.mozilla.org/ en-US/firefox/addon/10345 如果您有兴趣了解哪些函数(以及哪个文件)在您无法控制的页面上执行。

如果您有兴趣弄清楚您的哪个脚本正在执行,那么有多种方法。 使用 Firebug,您可以 console.log() 信息。 即使只是在代码中添加警报语句(虽然很烦人)也可以帮助以低技术含量的方式进行调试。 您还可以引发错误并捕获它们,然后使用错误的属性进行处理(请参阅: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error

但是,为什么这很重要? 如果脚本已经导致错误,那么很容易确定错误发生的位置。 如果根本与错误无关,那么知道它来自哪个文件有什么好处?

You may want to have a look at https://addons.mozilla.org/en-US/firefox/addon/10345 if you're interested in learning which functions (and thus which file) are executing on a page you don't control.

If you're interested in figuring out which of your scripts is executing, then there are a number of ways. With Firebug you could console.log() the information. Even just putting alert statements in your code (while annoying) can help debug in a low-tech way. You could also raise errors and catch them, then process using properties of the error (see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error)

However, why would this be important? If the script is causing errors already then it's easy enough to determine where the error is occurring. If it's not about errors at all, then what's the advantage in knowing which file it comes from?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文