Original: JS Magic Hall: Get the absolute path of the current script file
First, preface
When writing the module loader, getting the absolute path of the current script file as the base path is an essential step, let's explore this problem together!
Second, the implementation of the major browser mode
[a]. Chrome and FF
A very simple sentence is enough!
var getcurrabspath = function () { return document.currentScript.src;};
This takes advantage of the object document.currentscript , which returns the currently executing script element, and then invokes the SRC attribute of the script element to get the absolute path of the scripting file.
[b]. ie10+, Safari and Opera9
Extract absolute paths using the Error object's Stack property (ie10+), sourceURL Property (Safari), and StackTrace property (OPERA9)
var getcurrabspath = function () { var a = {}, stack; Try { a.b (); } Catch (e) { = E.stack | | e.sourceurl | | e.stacktrace; } var rextracturi =/(?: http|https|file): \/\/.*?\/.+?. js/, = rextracturi.exec (stack); return abspath[0"
[C]. ie5.5~9
Traverse a script tag in a document
varGetcurrabspath =function () {varScripts =document.scripts; varIsLt8 = ("'+ document.queryselector). IndexOf ('[native code]') === -1; for(vari = scripts.length-1, script; Script = scripts[i--];){ if(Script.readystate = = ='interative'){ returnIsLt8? Script.getattribute ('src',4): SCRIPT.SRC; } }};
Iii. Introduction of relevant knowledge
Ie5.5~9 the readystate of the script element to indicate the state of the scenario, respectively, with the following status values:
Uninitialized: not initialized
Loading: Loading
Loaded: Loading complete
Interative: In execution
Complete: Executed
You can listen for changes in the state of a SCRIPT element by subscribing to the onReadyStateChange event. Unfortunately, the loaded and complete states are in an indefinite sequence and are likely to appear only one, so it is recommended that when you add a SCRIPT element dynamically, the SRC attribute is set before the script element is added to the DOM tree. This allows the loaded and complete states to appear only one (although each request, which appears to be indeterminate), is better monitored.
Four, IE and FF under another way
By subscribing to the window.onerror event, the event handler will accept three parameters, Msg,url and num, respectively. Here the URL is the absolute path to the current script.
V. Summary
For complete Getcurrabspath, please visit https://github.com/fsjohnhuang/getCurrAbsPath/blob/master/lib/getCurrAbsPath.js
Respect the original, reprint please indicate from: http://www.cnblogs.com/fsjohnhuang/p/3903607.html, ^_^ Fat Boy John