Obtain the path of the current Javascript script file
Obtain the path of the current Javascript script file
Obtain the path of the current Javascript script file, which may be required in specific scenarios, such as writing module loaders or logging. There is no uniform method for all browsers. This article describes several situations.
(1). Standard Practice: src attribute of document. currentScript object
Applicable to Firefox 4 +, Chrome 29 +, Opera 16 +, and Safari 8 +.
var src = document.currentScript.src;
(2). Extract the file path from the stack attribute of the Error object
Applicable to IE10 +, Safari 7-, and Opera 15 -.
var e = new Error('err');var stack = e.stack || e.sourceURL || e.stacktrace || '';var rgx = /(?:http|https|file):\/\/.*?\/.+?.js/, var src = (rgx.exec(stack)||[])[0] || '';
If the browser does not support Error constructor, try... Catch to get an Error object.
Listen to the onerror event to process the Error object. The 2nd parameter of the callback function of the onerror event is src. The Code will not be pasted.
(3). Find the src of the last script element in the document. scripts set.
It is applicable to execution during Script Loading and not to calls after script initialization. No browser requirements.
var src = document.scripts[document.scripts.length - 1].src;
(4). Find the src of the script element whose readyState attribute is interative in the document. scripts collection.
Applicable to browsers earlier than IE9-. IE9. If the script. readyState attribute is interative, the script is being executed.
var scripts = document.scripts, src;for (var i = scripts.length - 1; i>=0; i--){ if (scripts[i].readyState === 'interative'){ src = scripts[i].src; break; }}
This article only provides an analysis of ideas. If you need to use it in a product, you need to handle the judgment of various applicable situations. Someone created a JS function (getCurrAbsPath. js) for processing.