0

I have a JavaScript file, which needs to know from which location it is loaded. My requirement is similar to How may I reference the script tag that loaded the currently-executing script?

I am using

document.currentScript;

to get the script path. But this implementation is breaking if my JavaScript file is loaded using jQuery's getScript() Method:

$(document).ready(function(){
  $("button").click(function(){
    $.getScript("my_script.js");
   });
});

When I do this, document.currentScript always returns null. Is there a work around to fix this issue?

Community
  • 1
  • 1
Vishvesh
  • 512
  • 8
  • 21
  • `$.getScript` doesn't use a script tag, it uses ajax with the `script` dataType to get and load the script, which is why `currentScript` probably is null. Why do you need to know which location the script was loaded from, it seems like a X/Y problem, and the really simple solution is to just check for a certain element in the current DOM to see what page you're on. – adeneo Jan 11 '16 at 15:36
  • My script file could change regularly and I have no control over who uses it. So if my script is not loaded from my domain, I simply log a message indicating to developers that they should check if script has been updated. Can you please share more information on "check for a certain element in the current DOM to see what page you're on." – Vishvesh Jan 11 '16 at 16:30
  • Did you try using `document.domain` to get the current domain in your script file – adeneo Jan 11 '16 at 16:31
  • Hey Thanks. This gives me the domain name. document.documentURI gives the complete URL. Can you please post this as the answer? – Vishvesh Jan 11 '16 at 16:44

1 Answers1

0

Try using $.ajaxSetup() , beforeSend

$.ajaxSetup({
  beforeSend:function(jqxhr, settings) {
    // do stuff with path to current `url`
    console.log(settings.url)
  }
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • I added this before making call to "getScript("my_script.js");". The log in this method gives a url, but how do I access the information in my script file. Since my script is not added to script dataType. – Vishvesh Jan 11 '16 at 16:35
  • Is requirement to return text of `"my_script.js"` ? – guest271314 Jan 11 '16 at 16:39
  • yes. document.documentURI seems to be working. But I need to test it. – Vishvesh Jan 11 '16 at 16:45