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

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

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



        
4条回答
  •  盖世英雄少女心
    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];
    

提交回复
热议问题