Last active
May 16, 2021 13:11
-
-
Save adamasantares/04cf84e3a99326a4d73f to your computer and use it in GitHub Desktop.
__FILE__ and __DIR__ in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* __DIR__ & __FILE__ for JavaScript (was tested in IE 7-10) | |
* This definition must be inserted at root of script file, outside of any function. | |
*/ | |
(function(w,d){ | |
var u=null; | |
w.__FILE__=(function(){ | |
try{u();}catch(err){ | |
if(err.stack){ | |
u=(/(http[s]?:\/\/.*):\d+:\d+/m).exec(err.stack); | |
if(u&&u.length>1){ return u[1]; } | |
} | |
u = (d.scripts.length>0) ? d.scripts[d.scripts.length-1].src : ""; | |
if (u.length > 0 && u.indexOf("://") < 0 && u.substring(0,1) != "/" ){ | |
u = location.protocol + "//" + location.host + "/" + u; | |
} | |
return u; | |
} | |
})(); | |
w.__DIR__=(function(f){ | |
f=(/^(.*\/)[a-z0-9 -_]+\.[a-z]+$/i).exec(f); | |
return (f&&f.length>1)?f[1]:""; | |
})(w.__FILE__); | |
})(window, document); | |
console.log(__FILE__); | |
console.log(__DIR__); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* __DIR__ & __FILE__ for JavaScript (was tested in IE 7-10) | |
* This definition must be inserted at root of script file, outside of any function. | |
*/ | |
(function(w,d){var u=null;w.__FILE__=(function(){try{u();}catch(err){if(err.stack){u=(/(http[s]?:\/\/.*):\d+:\d+/m).exec(err.stack);if(u&&u.length>1){return u[1];}}u=(d.scripts.length>0)?d.scripts[d.scripts.length-1].src:"";if(u.length>0 && u.indexOf("://")<0 && u.substring(0,1)!="/"){u=location.protocol+"//"+location.host+"/"+u;}return u;}})();w.__DIR__=(function(f){f=(/^(.*\/)[a-z0-9 -_]+\.[a-z]+$/i).exec(f);return (f&&f.length>1)?f[1]:"";})(w.__FILE__);})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment