Miawa
Miawa

Reputation: 312

Get current running javascript filename after document is loaded

Is any way to get the file info (file name, path) of a javascript file after the document is ready, without knowing how many scripts or the order how they are loaded?

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 file js2.js 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 don't know the order of the loaded scripts.

Upvotes: 4

Views: 5657

Answers (5)

Aikon Mogwai
Aikon Mogwai

Reputation: 5225

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

document.getElementsByTagName('script') return HTMLCollection of page scripts. Last element is current script. HTMLCollection doesn't have method to get last, but after convert colliection by [].slice.call to Array we can call pop to do it. Finally getAttribute return desired filename.

Same code can used to passing arguments to js-script

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359786

Perhaps a full answer would be more helpful than my comments. If you put this code into js2.js, you'll get what you want. The key is to capture scriptLocation in a piece of code which runs synchronously with the loading the file, which means not in a callback.

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);
}

Upvotes: 3

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

To get Line Number and filename from Error.stack eg:

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

See Error.stack

For browser compatibility, see previous SO question

Upvotes: 3

Vince
Vince

Reputation: 1527

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

If I correctly understood your question, that should do the trick.

Upvotes: 0

Mister Epic
Mister Epic

Reputation: 16723

Not entirely sure what you're after, but if you want to get reference to all the scripts loaded in the DOM, you would simply do:

var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
     var scriptLocation = scripts[i].src;
}

Upvotes: 1

Related Questions