Get The Current Script’s Path

There were some tricky functions posted on the intarwebs for grabbing the URL of the current script’s directory (not the script itself). Most of them used some wacky RegEx trickery, but I figured there HAD to be a simpler way. So I made this utility function, which DOES use jQuery, but only because it’s SO DARN EASY to grab the DOM element I need to work with (and I’m already using jQuery in my project anyway).

Here it is:

function getScriptDir() {
    var src = $('script[src]').last().attr('src');
    var path = src.split('/');
    return path.join('/')+'/';

What it does:

Gets the ‘src’ attribute for the last script on the page (DO NOT RUN THIS FUNCTION AFTER THE DOM LOADS – IT WON’T WORK), which should be the script where you call the function. Then it splits the components at the ‘/’ separators, knocks off the last element in the array (which is the script file itself), and joins it back together with slashes and adds another on the end for ease-of-use.

There you go. Feel free to use it wherever you want (I’m sure tons of people use this exact technique anyway, but whatever). Maybe you can even cut out the jQuery part for a fully-native JavaScript implementation (or maybe I will later).


2 thoughts on “Get The Current Script’s Path

  1. Pingback: Some code snippet updates… | Error 601

  2. Pingback: Get The Current Script’s Path (non-jQuery) | Error 601

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s