Gets the path to the current JavaScript script file
Gets the path to the current JavaScript script file, which may be required under a specific scenario, such as writing a module loader or logging. There is no uniform method for all browsers, this article is described in several cases.
(1). Standard practice: src attribute of Document.currentscript object
For Firefox 4+, Chrome 29+, Opera 16+, Safari 8+.
var src = document.currentScript.src;
(2). Extract the file path from the Stack property of the Error object
For ie10+, Safari 7-, Opera 15-.
varnewError(‘err‘);var‘‘;var/(?:http|https|file):\/\/.*?\/.+?.js/var src = (rgx.exec(stack)||[])[0‘‘;
If the browser does not support the error constructor, you can also get an Error object through Try...catch.
Listen to the OnError event to handle the Error object, as well as the principle. The 2nd parameter of the callback function for the onerror event is SRC. The code will not be posted.
(3). Find the src of the last script element in the Document.scripts collection
Applies to scenarios that are executed during script loading and does not apply to calls after script initialization is complete. There is no requirement for the browser.
var src = document.scripts[document.scripts.length1].src;
(4). Find the src of the script element with the ReadyState property interative in the Document.scripts collection
Suitable for ie9-. IE9 The following browsers, the Script.readystate property is interative to indicate that the script is executing.
vardocument.scripts, src;for (var1; i>=0; i--){ if‘interative‘){ src = scripts[i].src; break; }}
This article only provides the idea analysis, if needs to use in the product, needs to handle each kind of application situation judgment. Someone has created a JS function (getcurrabspath.js) to handle.
Gets the path to the current JavaScript script file