Skip to content

JavaScript version of PHP __FILE__ or __DIR__

This is one of those issues I keep coming back to.  I need a way to get the path of the current JavaScript file.  Something analogous to the PHP __DIR__ constant or dirname(__FILE__).

Found something close on Stack Overflow.  The solution there gets the entire file.  A bit of substring and lastIndexOf and I had a solution.

var scriptSource = (function() {
    var scripts = document.getElementsByTagName('script');
    var script = scripts[scripts.length - 1].src;
    return script.substring(0, script.lastIndexOf('/')) + '/';
}());

alert(scriptSource);

Looks to work in IE8, FF3.6, and Chrome. Don’t have other versions to test right now, but I can’t see why it wouldn’t work.

Published inProgramming

2 Comments

  1. The lesson for the day is to RTFM. I was planning on using this for a WordPress plugin for an Ajax call. Turns out WP has a pluggable Ajax file already and a JavaScript variable loaded with the path, so don’t even need this.

    Still something useful for the bag of tricks though…

  2. Bit of a flaw though. It’s dependent on the order of loading, so it’s possible that it’ll actually pull the path of the last JS file loaded rather than the one you’re interested in. What I wound up doing was also to check that the src ended with the right filename. Not quite as clean, but it does work.

Leave a Reply

Your email address will not be published. Required fields are marked *