Get The Current Script’s Path (non-jQuery)

So, I use this snippet quite a lot, usually for loading a CSS file that’s in the same folder as the script file. I’ve used it with jQuery since it’s a very popular library (and we use it in the web app I work on), but this function can be performed without jQuery using the document.querySelectorAll(‘sel’) method.

function getScriptDir() {
    var scripts, src, path;
    scripts = document.querySelectorAll("script[src]");
    src = scripts[scripts.length-1].src;
    if (src.indexOf("/") !== -1) {
        path = src.split("/");
        path.splice(path.length - 1, 1);
        return path.join("/") + "/";
    }
    else {
        return "";
    }
}

This works because the script where this function resides doesn’t know about any other files that come after it (just be sure to fire it right away – DO NOT wait for the entire DOM to load).

Here are previous versions of this function…

The jQuery version is in this post:
https://error601.wordpress.com/2014/08/21/some-code-snippet-updates/

The “original” (included here for reference, but not recommended since it can’t handle src attributes without a slash, which is dumb):
https://error601.wordpress.com/2014/02/12/get-the-current-scripts-path/

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s