How to get the location (src) of a javascript file?

前端 未结 4 1337
囚心锁ツ
囚心锁ツ 2020-12-06 07:02

How can a javascript file know where it is located? For example:



        
相关标签:
4条回答
  • Try this:

    function getScriptSourceName(name){
        var scripts = document.getElementsByTagName('script');
        for (i=0;i<scripts.length;i++){
            if (scripts[i].src.indexOf(name) > -1)
                return scripts[i].src;
        }
    }
    
    getScriptSourceName('howdy.js');
    
    0 讨论(0)
  • 2020-12-06 07:46

    Give this script tag an id, and write:

    var src = document.getElementById('scriptID').attributes['src'];
    
    0 讨论(0)
  • 2020-12-06 07:46

    Try:

    document.scripts[document.scripts.length-1]; // add .src to get href
    //or
    document.getElementsByTagName("script")[document.getElementsByTagName("script").length-1];
    //for (maybe) better compatibility
    

    Which gets the last script in the DOM. If your script is being executed while it is being loaded, this will return the right element.

    Save it to a variable for use in functions which will be used later.

    var thisScript = document.scripts[document.scripts.length-1];
    
    0 讨论(0)
  • 2020-12-06 07:47

    In the moment in which the current script is being executed, will be the last script element in the DOM, therefore you can get it by:

    var scripts = document.getElementsByTagName('script'),
        currentScriptSrc = scripts[scripts.length-1].src;
    

    Check this example that loads this script.

    Edit: Taking in consideration the @kangax's comment, about the async and defer attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script elements on the page, examining its src attribute, some libraries like Scriptaculous.us use this technique, for example:

    var scripts = document.getElementsByTagName('script'),
        len = scripts.length,
        re = /howdy\.js$/,
        src, howdyScriptSrc;
    
    while (len--) {
      src = scripts[len].src;
      if (src && src.match(re)) {
        howdyScriptSrc = src;
        break;
      }
    }
    ​
    
    0 讨论(0)
提交回复
热议问题