Skip to content

Instantly share code, notes, and snippets.

@subchen
Last active August 29, 2015 14:08
Show Gist options
  • Save subchen/8ea9e07fe8a5a03dbe33 to your computer and use it in GitHub Desktop.
Save subchen/8ea9e07fe8a5a03dbe33 to your computer and use it in GitHub Desktop.
获取 JavaScript 脚本自身的 URL
(function(window, $, jetbrick) {
/**
* Get the current script's URL by throwing an `Error` and analyzing it.
*
* @returns String or `undefined`
* @private
*/
var getCurrentScriptUrlFromErrorStack = function(stack) {
var url, matches;
if (typeof stack === "string" && stack) {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
} else {
matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
}
}
}
return url;
};
/**
* Get the current script's URL.
*
* @returns String or undefined
* @private
*/
jetbrick.getCurrentScriptUrl = function() {
var document = window.document;
if (document.currentScript && document.currentScript.src) {
return document.currentScript.src;
}
var scripts = document.getElementsByTagName("script");
if (scripts.length === 1) {
return scripts[0].src || undefined;
}
var url;
if ("readyState" in scripts[0]) {
for (i = scripts.length; i--;) {
if (scripts[i].readyState === "interactive" && (url = scripts[i].src)) {
return url;
}
}
}
if (document.readyState === "loading" && (url = scripts[scripts.length - 1].src)) {
return url;
}
// Get the current script's URL by throwing an `Error` and analyzing it.
try {
throw new Error();
} catch (e) {
return e.sourceURL || e.fileName || getCurrentScriptUrlFromErrorStack(e.stack);
}
return undefined;
};
})(window, jQuery, window.jetbrick || (window.jetbrick = {}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment