Programing

JavaScript-호출되는 스크립트의 URL을 어떻게 얻습니까?

lottogame 2020. 10. 26. 07:36
반응형

JavaScript-호출되는 스크립트의 URL을 어떻게 얻습니까?


다음 http://site1.com/index.html과 같이 파일에 myscript.js를 포함 합니다.

<script src=http://site2.com/myscript.js></script>

"myscript.js"에서 URL " http://site2.com/myscript.js "에 액세스하고 싶습니다 . 다음과 같은 것을 갖고 싶습니다.

function getScriptURL() {
    // something here
    return s
}

alert(getScriptURL());

위에서 언급 한 index.html에서 호출하면 " http://site2.com/myscript.js "를 경고 합니다.


에서 http://feather.elektrum.org/book/src.html :

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

이제 변수 myScript에 스크립트 dom 요소가 있습니다. 을 사용하여 src URL을 가져올 수 있습니다 myScript.src.

이것은 스크립트의 초기 평가의 일부로 실행되어야합니다. Javascript 네임 스페이스를 오염시키지 않으려면 다음과 같이 할 수 있습니다.

var getScriptURL = (function() {
    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var myScript = scripts[index];
    return function() { return myScript.src; };
})();

스크립트 태그에 id 속성을 추가 할 수 있습니다 (헤드 태그 안에 있더라도).

<script id="myscripttag" src="http://site2.com/myscript.js"></script>

다음과 같이 src에 액세스합니다.

document.getElementById("myscripttag").src

물론 id 값은 스크립트를 포함하는 모든 문서에 대해 동일해야하지만 큰 불편은 없다고 생각합니다.


DOM 및 querySelector를 사용하여 특정 스크립트를 수행 할 수 있습니다.

var dir = document.querySelector('script[src$="myscript.js"]').getAttribute('src');
var name = dir.split('/').pop(); 
dir = dir.replace('/'+name,"");

IE를 제외한 모든 지원

document.currentScript

지연 로딩 및 비동기 스크립트 태그로 작동하는 스크립트 경로를 찾기 위해 클래스를 작성했습니다.

스크립트와 관련된 템플릿 파일이 있었기 때문에 하드 코딩하는 대신 클래스를 만들어 경로를 자동으로 만들었습니다. 전체 소스는 여기 github에 있습니다.

얼마 전 나는 arguments.callee를 사용하여 비슷한 작업을 시도했지만 최근 MDN 에서 Strict 모드에서는 허용되지 않는다고 읽었습니다 .

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('\n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:\/\//)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}

if you have a chance to use jQuery, the code would look like this:

$('script[src$="/myscript.js"]').attr('src');

Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript
For IE you can do document.querySelector('script[src*="myscript.js"]')
so :

function getScriptURL(){
 var script =  document.currentScript || document.querySelector('script[src*="myscript.js"]')
 return script.src
}

Following code lets you find the script element with given name

var scripts = document.getElementsByTagName( 'script' );
        var len = scripts.length
        for(var i =0; i < len; i++) {
            if(scripts[i].src.search("<your JS file name") > 0 && scripts[i].src.lastIndexOf("/") >= 0) {
                absoluteAddr = scripts[i].src.substring(0, scripts[i].src.lastIndexOf("/") + 1);
                break;
            }
        }

Can't you use location.href or location.host and then append the script name?

참고URL : https://stackoverflow.com/questions/2976651/javascript-how-do-i-get-the-url-of-script-being-called

반응형