Note that there are some explanatory texts on larger screens.

plurals
  1. POGet the url of currently executing js file when dynamically loaded
    text
    copied!<p>So I'm trying to load a script dynamically and figure out the URL path at which that script was loaded. So some guy gave me a pretty awesome solution to this problem if the scripts are statically loaded ( <a href="https://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currenctly-executing-javascript-code">How to get the file-path of the currently executing javascript code</a> ). But I need a dynamically loaded solution. For example:</p> <pre><code>$(function() { $.getScript("brilliant.js", function(data, textStatus) { // do nothing }); }); </code></pre> <p>where "brilliant.js" has:</p> <pre><code>var scripts = document.getElementsByTagName("script"); var src = scripts[scripts.length-1].src; alert("THIS IS: "+src); </code></pre> <p>Ideally this should either print out "brilliant.js" or "&lang;hostname+basepath&rang;/brilliant.js"</p> <p>Currently brilliant.js works for statically included scripts, but not for scripts included dynamically (like with $.getScript). Anyone have any ideas? Is there somewhere in the dom that stores all the scripts that have been loaded?</p> <p>EDIT: Andras gave a pretty good solution, though it probably only works for jQuery. Since that's probably the most popular library, and definitely what I'm going to be using. It can probably be extended for other libraries as well. Here's my simplified version:</p> <pre><code>var scriptUri; curScriptUrl(function(x) { scriptUri = x; alert(scriptUri); }); function curScriptUrl(callback) { var scripts = document.getElementsByTagName("script"); var scriptURI = scripts[scripts.length-1].src; if(scriptURI != "") // static include { callback(scriptURI); }else if($ != undefined) // jQuery ajax { $(document).ajaxSuccess(function(e, xhr, s) { callback(s.url); }); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload