Home >Web Front-end >JS Tutorial >JS gets the absolute path of the current script file_javascript tips
When writing a module loader, it is an essential step to obtain the absolute path of the current script file as the base path. Let’s discuss this issue together!
1. Implementation methods of major browsers
[a]. Chrome and FF
A super simple sentence is enough!
var getCurrAbsPath = function(){ return document.currentScript.src; };
The object document.currentScript is used here, which returns the currently executed script element; then the absolute path of the script file can be obtained by calling the src attribute of the script element.
[b]. IE10+, Safari and Opera9
Use the stack attribute (IE10+), sourceURL attribute (Safari) and stacktrace attribute (Opera9) of the Error object to extract the absolute path
var getCurrAbsPath = function(){ var a = {}, stack; try{ a.b(); } catch(e){ stack = e.stack || e.sourceURL || e.stacktrace; } var rExtractUri = /(?:http|https|file):\/\/.*?\/.+?.js/, absPath = rExtractUri.exec(stack); return absPath[0] || ''; };
[C]. IE5.5~9
Traverse the script tags in the document
var getCurrAbsPath = function(){ var scripts = document.scripts; var isLt8 = ('' + document.querySelector).indexOf('[native code]') === -1; for (var i = scripts.length - 1, script; script = scripts[i--];){ if (script.readyState === 'interative'){ return isLt8 ? script.getAttribute('src', 4) : script.src; } } };
2. Introduction to relevant knowledge
The readyState of script under IE5.5~9 indicates the status of the script element, which has the following status values:uninitialized: not initialized
loading: Loading
loaded: Loading completed
interactive: executing
complete: execution completed
You can listen to script element state changes by subscribing to the onreadystatechange event. But unfortunately, the loaded and complete states appear in an uncertain order and only one of them may appear. Therefore, it is recommended that when adding a script element dynamically, you first set the src attribute and then add the script element to the DOM tree, so that the loaded and complete states only One of them will appear (although which one appears each time it is requested), which is easier to monitor.
3. Another way under IE and FF By subscribing to the window.onerror event, the event handler function will accept three parameters, namely msg, url and num. The url here is the absolute path of the current script.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.