[ACCEPTED]-What is my script src URL?-src

Accepted answer
Score: 41

Put this in the js file that needs to know 3 it's own url.

Fully Qualified (eg http://www.example.com/js/main.js):

var scriptSource = (function(scripts) {
    var scripts = document.getElementsByTagName('script'),
        script = scripts[scripts.length - 1];

    if (script.getAttribute.length !== undefined) {
        return script.src
    }

    return script.getAttribute('src', -1)
}());

Or As it appears in source (eg /js/main.js):

var scriptSource = (function() {
    var scripts = document.getElementsByTagName('script'),
        script = scripts[scripts.length - 1];

    if (script.getAttribute.length !== undefined) {
        return script.getAttribute('src')
    }

    return script.getAttribute('src', 2)
}());

See http://www.glennjones.net/Post/809/getAttributehrefbug.htm for explanation 2 of the getAttribute parameter being used (it's an IE 1 bug).

Score: 39

For recent browsers, you can use document.currentScript 11 to get this information.

var mySource = document.currentScript.src;

The upside is that 10 it's more reliable for scripts that are 9 loaded asynchronously. The downside is that 8 it's not, as best I know, universally supported. It 7 should work on Chrome >= 29, FireFox 6 >= 4, Opera >= 16. Like many useful 5 things, it doesn't seem to work in IE.

When 4 I need to get a script path, I check to 3 see if document.currentScript is defined, and, if 2 not, use the method described in the accepted 1 answer.

if (document.currentScript) {
    mySource = document.currentScript.src;
} else {
    // code omitted for brevity
}

https://developer.mozilla.org/en-US/docs/Web/API/document.currentScript

Score: 6

As it appears in source (e.g. /js/main.js), this is cross-browser:

var scriptSource = (function() 
{ 
    var scripts = document.getElementsByTagName('script'), 
        script = scripts[scripts.length - 1]; 

    //No need to perform the same test we do for the Fully Qualified
    return script.getAttribute('src', 2); //this works in all browser even in FF/Chrome/Safari
}()); 

Fully Qualified (e.g. http://www.example.com/js/main.js):

After some tests 2 it seems hard to get the fully qualified one in a cross-browser 1 way. The solution suggested by Crescent Fresh does not work in IE8 to get the fully qualified, even if it works in IE7

Score: 5

This method work with defer, async and lazy 7 loading Since you know the filename of your 6 script, and if it will be unique

/* see  
 * http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656
 * http://www.glennjones.net/Post/809/getAttributehrefbug.htm
 * 
 * iterate all script to find script with right filename
 * this work with async and defer (but your script MUST have a unique filemane)
 * mozilla support document.currentScript and we use it, if is set
 *
 * this will not work with local script loaded by jQuery.getScript(),
 * since there is no script tag added into the dom. the script is only evaluated in global space.
 * http://api.jquery.com/jQuery.getScript/
 *  
 * to fix this odd, you can add a reference in meta ( meta[name=srcipt][content=url] )
 * when you load the script
 */
var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename 
var scriptUrl = (function() {
    if (document.currentScript) { // support defer & async (mozilla only)
        return document.currentScript.src;
    } else {
        var ls,s;
        var getSrc = function (ls, attr) {
            var i, l = ls.length, nf, s;
            for (i = 0; i < l; i++) {
                s = null;
                if (ls[i].getAttribute.length !== undefined) { 
                    s = ls[i].getAttribute(attr, 2);                    
                }               
                if (!s) continue; // tag with no src
                nf = s;
                nf = nf.split('?')[0].split('/').pop(); // get script filename
                if (nf === scriptFilename) {
                    return s;
                }
            }
        };          
        ls = document.getElementsByTagName('script');
        s = getSrc(ls, 'src');
        if ( !s ) { // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url]
            ls = document.getElementsByTagName('meta');             
            s = getSrc(ls, 'content');
        }           
        if ( s ) return s;
    }
    return '';
})();

var scriptPath =  scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/";

a jquery 5 plugin template with it: https://github.com/mkdgs/mkdgs-snippet/blob/master/javascript/jquery.plugins.template.js

note: this will 4 not work with local script loaded by jQuery.getScript(), since 3 there is no script tag added into the dom. the 2 script is only evaluated in global space. http://api.jquery.com/jQuery.getScript/

to 1 fix it you can do something like:

function loadScript(url,callback) {     

    if ( $('[src="'+url+'"]').length ) return true; // is already loaded    

    // make a reference of the loaded script
    if ( $('meta[content="'+url+'"]', $("head")).length ) return true; // is already loaded 
    var meta = document.createElement('meta');
    meta.content = url;
    meta.name = 'script';
    $("head").append(meta);

    return $.ajax({
          cache: true,
          url: u,
          dataType: 'script',
          async: false,
          success : function (script) {                     
                try { 
                    if ( typeof callback == 'function' ) callback();    
                } catch (error) { 
                    //console.log(error);
                }
          }
     });
}
Score: 0

If this is a strictly client solution, yours 6 sounds pretty good.

If you are writing code 5 on the server, you could probably just populate 4 a div/hidden field/(insert your fave HTML 3 element here) with the fully resolved URL 2 to the script, and pick that up with your 1 javascript on the clientside.

Score: 0

You may want to have a look at https://addons.mozilla.org/en-US/firefox/addon/10345 if you're 16 interested in learning which functions (and 15 thus which file) are executing on a page 14 you don't control.

If you're interested in 13 figuring out which of your scripts is executing, then 12 there are a number of ways. With Firebug 11 you could console.log() the information. Even just putting 10 alert statements in your code (while annoying) can 9 help debug in a low-tech way. You could 8 also raise errors and catch them, then process 7 using properties of the error (see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error)

However, why 6 would this be important? If the script is 5 causing errors already then it's easy enough 4 to determine where the error is occurring. If 3 it's not about errors at all, then what's 2 the advantage in knowing which file it comes 1 from?

More Related questions