Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,413
    Thanks
    11
    Thanked 595 Times in 575 Posts

    get external script url from within

    once upon a time, we were able to determine the url of our scripts with a small snip:
    Code:
    [].slice.call(document.getElementsByTagName("script"), -1)[0].src
    The ability is great for debugging, tracking versions, machine-building documentation, auditing <html manifest=, pre-fetching your code to localStorage via ajax, making more meaningful log entries, building dependency pyramids for modules, a poor man's domain enforcer, and many other practical uses.



    once document.createElement("script") - based loaders entered the picture, that capability became unreliable.

    you could iterate all the script tags and try to match up your src, but if the files get renamed, the code breaks, causing maintenance headaches.


    i figured out a neat way to use the error object to infer the executing script's URL.

    While it doesn't work in past versions of IE, it DOES work on mobile, FF, Chrome, and IE 10, so it should be great going forward and in the mobile/tablet space today.

    unlike guessing and checking urls, this method requires no per-edit or per-file customization.

    Note that it returns the name of the file that contains the __filename() function, not the name of the file that calls it.

    This makes it especially nice for checking-in modules, since you can simply attach it as a method to exports, or whatever your module's namespace happens to be. You might just want to run it once and save the string URL as a property on the module, a constructor, or something else, it's super-simple to use in many ways.



    Code:
    function __filename(){
       try{self.s0m3741ng()}catch(y){
    	return "http://" + 
    	 String(y.fileName || y.file || y.stack || y + '')
    	 .split(/:\d+:\d+/)[0].split("http://")[1];
        } 
    }//end __filename()
    
    
    // example usage: alert(  __filename()    );


    The function returns "http://undefined" if pasted into a firebug/inspector console (for reasons i hope are obvious to you) but i made a simple online demo if you want to "kick the tires".
    Last edited by rnd me; 11-06-2012 at 06:25 AM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •