Get current javascript file name after loading document

Is it possible to get information about the file (file name, path) of the javascript file after the document is ready without knowing how many scripts or the order in which they are downloaded?

i.e.

<html>
  <head>
    <script src="http://www.example.ex/js/js1.js" type="text/javascript">
    <script src="http://www.example.ex/javascript/js2.js" type="text/javascript">
    <script src="http://www.example.ex/scripts/js3.js" type="text/javascript">
    <...>

Where the js2.js file has something like this:

$(document).ready(function() {
  // get the filename "js2.js"
}

I could do

var scripts = document.getElementsByTagName("script"),
    scriptLocation = scripts[1].src;

but the index "[1]" must be dynamic, because I do not know the order of the loaded scripts.

+4
source share
5 answers

, , . js2.js, , . , scriptLocation , , .

var scripts = document.getElementsByTagName("script"),
    scriptLocation = scripts[scripts.length - 1].src;

$(document).ready(function() {
  // logs the full path corresponding to "js2.js"
  console.log(scriptLocation);
}
+3

Error.stack :

console.log((new Error).stack.split("\n"));

. Error.stack

, . SO

+2

, , , DOM, :

var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
     var scriptLocation = scripts[i].src;
}
+1
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
    if (scripts[i].src.match(/<desired filename>/) {
        scriptLocation = scripts[i];
    }
}

, .

0
var scriptName = [].slice.call(document.getElementsByTagName('script')).pop().getAttribute('src');

document.getElementsByTagName('script')return HTMLCollectionpage scripts. The last element is the current script. HTMLCollectionThere is no method for obtaining the latter, but after converting the colliection to [].slice.callinto, Arraywe can call popto do this. Finally getAttributereturns the desired file name.

The same code can be used to pass arguments to js-script

<script src="file.js" args="arg1;arg2">
...
var args = [].slice.call(document.getElementsByTagName('script')).pop().getAttribute('args').split(';');
0
source

All Articles