JS Gets the absolute path to the current script file

  • 2021-01-19 22:00:44
  • OfStack

When writing a module loader, it is necessary to get the absolute path of the current script file as the base path. Let's discuss this next step.

1. How each browser implements it

[r]. a Chrome and FF

A super simple sentence is enough!


var getCurrAbsPath = function(){
 return document.currentScript.src;
};

We use the object document.currentScript, which returns the currently executed script element; Then call the src attribute of the script element to get the absolute path to the script file.

[b]. IE10+, Safari and Opera9

Absolute paths are extracted using the stack attributes (IE10+), sourceURL attributes (Safari), and stacktrace attributes (Opera9) of the Error object


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

Iterate through the script tag 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. Relevant knowledge introduction

Under IE5. 5 ~ 9 script readyState said the script elements of the state, state of respectively have the following values:

uninitialized: Uninitialized

loading: Loading

loaded: Loading completed

interative: In execution

complete: That's it

You can listen for changes in the state of script elements by subscribing to onreadystatechange events. But unfortunately loaded and indefinite complete state and order and may have only one, it is recommended that the dynamic addition script elements, first set src properties and then add script elements to the DOM tree, such loaded and complete state there will be only one (although each request, which is variable), better monitoring.

3. Another method under IE and FF

By subscribing to the window.onerror event, the event handler takes three arguments, msg,url, and num. Here, url is the absolute path to the current script.

The above is all the content of this article, I hope to help you learn.


Related articles: