0

In struggling with a solution to this problem I've run into another, related issue: how can I determine what the location of a running script is? (no, it's not document.location as that will tell you the location of the page including the script)

so, with:

- a.html -

<script type="text/javascript" src="/my/path/myscript.js"></script>

- myscript.js -

var myLoc = document.location; // what to use instead?
Community
  • 1
  • 1
ekkis
  • 9,804
  • 13
  • 55
  • 105
  • possible duplicate of [Get script path](http://stackoverflow.com/questions/2161159/get-script-path) – Jon Egerton Nov 23 '11 at 22:42
  • What sort of answer do you expect; the URL of the JavaScript file? – David Thomas Nov 23 '11 at 22:42
  • Is the script your trying to find actually in the page as a `script` tag or is it dynamically loaded in through ajax? if it's the latter I'm not sure you can – Chris Nov 23 '11 at 22:43
  • @DavidThomas, what I need is something that's available whilst the script is running that I can use to correlate against the array of scripts loaded and generally available as `$('script')` – ekkis Nov 23 '11 at 23:17
  • @Chris, it's the latter (if you look at the link I included above you'll see where I'm coming from) but I'm building the script tags at runtime before the code runs and I can include any sort of information in the tag itself... what I don't have is a way to tell which of the entries in the array of scripts corresponds to the currently running script (and no, it isn't the last one added - unfortunately, otherwise I'd be done) – ekkis Nov 23 '11 at 23:20

2 Answers2

0

If you can select the script, you can get its src.

var scripts = document.getElementsByTagName('script');

var loc = scripts[ 0 ].src;

This gives you the src of the first script element found.

You can use jQuery to do it too.

var loc = $('script').eq(0).prop('src');

or for older jQuery versions:

var loc = $('script').eq(0).attr('src');

$(function() {
    $.ajax({
         type: 'get', cache: false, url: '/svc.html',
         success: function(h) {

             var d = document.createElement('div');
             d.innerHTML = h;

             var scripts = d.getElementsByTagName('script');

             alert( scripts[ scripts.length - 1 ].src );

             $('#main').html( d.childNodes );
         }
    });
});
RightSaidFred
  • 11,209
  • 35
  • 35
  • if you read through the problem I was trying to solve originally, you'll understand this is not viable – ekkis Nov 23 '11 at 23:22
0

so the answer to this is two-fold: 1) if the script was loaded by a tag directly, one can use RightSaidFred's approach consisting of picking up the last entry in the list of scripts, 2) for scripts that are loaded in a page that was loaded via ajax, the solution is the plugin at: Where are scripts loaded after an ajax call?

Community
  • 1
  • 1
ekkis
  • 9,804
  • 13
  • 55
  • 105