是否有一种简单可靠的方法来确定当前正在执行的JavaScript文件的URL(在网页内)?
我唯一想到的是扫描DOM src
以查找所有脚本属性以查找当前文件的引用方式,然后通过应用它来计算绝对URL document.location
.任何人都有其他想法,是否有一些我完全忽略的超级简单方法?
更新:通过DOM访问的脚本元素已经具有src
包含完整URL 的属性.我不知道它是多么普遍/标准,但是你可以使用getAttribute("src")
哪个将返回[X] HTML中的任何原始属性值.
把它放在需要知道它自己的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.htmgetAttribute
(这是一个IE错误).
对于最近的浏览器,您可以使用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
因为它出现在源(例如/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中有效
此方法适用于延迟,异步和延迟加载,因为您知道脚本的文件名,并且文件名是否唯一
/* 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); } } }); }