program story

외부 스크립트가로드되었는지 확인

inputbox 2020. 11. 23. 08:06
반응형

외부 스크립트가로드되었는지 확인


jquery 플러그인을 만들고 있으며 외부 스크립트가로드되었는지 확인하고 싶습니다. 이것은 내부 웹 앱용이며 스크립트 이름 / 위치를 일관되게 유지할 수 있습니다 (mysscript.js). 이것은 또한 페이지에서 여러 번 호출 할 수있는 ajaxy 플러그인입니다.

스크립트가로드되지 않았 음을 확인할 수 있으면 다음을 사용하여로드합니다.

jQuery.getScript()

동일한 스크립트가 페이지에 두 번 이상로드되는 것을 원하지 않기 때문에 스크립트가로드되었는지 어떻게 확인할 수 있습니까? 이것은 스크립트 캐싱 때문에 걱정할 필요가없는 것입니까?

업데이트 : 조직에서이 플러그인을 사용하는 사람을 제어 할 수 없으며 스크립트가 특정 ID가 있거나없는 페이지에 아직 존재하지 않도록 강제 할 수 없지만 스크립트 이름은 항상 다음과 같은 위치에 있습니다. 같은 이름. 스크립트 이름을 사용하여 실제로로드되었는지 확인할 수 있기를 바랍니다.


스크립트가 전역 공간에 변수 또는 함수를 생성하는 경우 존재 여부를 확인할 수 있습니다.

외부 JS (전역 범위 내)-

var myCustomFlag = true;

그리고 이것이 실행되었는지 확인하려면 :

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

최신 정보

<script>모든 <script>요소 를 선택 하고 해당 src속성을 확인 하여 문제 태그 가 있는지 확인할 수 있습니다 .

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

또는이 .filter()기능을 선택기에 바로 적용 할 수 있습니다 .

var len = $('script[src="<external JS>"]').length;

@jasper의 대답은 완전히 정확하지만 최신 브라우저에서는 표준 Javascript 솔루션이 다음과 같을 수 있습니다.

function isScriptLoaded(src)
{
    return document.querySelector('script[src="' + src + '"]') ? true : false;
}

저를 솔루션으로 이끄는 모든 답변 덕분에 방법을 알게 된 지금은 매우 간단했습니다. 스크립트의 소스를 지정하기 위해 $ .getScript ()를 포기해야했습니다 ... 때로는 수동으로 작업하는 것이 가장 좋습니다.

해결책

//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length; 

if (len === 0) {
        alert('script not loaded');

        loadScript('Javascript/MyScript.js');

        if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
            alert('still not loaded');
        }
        else {
            alert('loaded now');
        }
    }
    else {
        alert('script loaded');
    }


function loadScript(scriptLocationAndName) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptLocationAndName;
    head.appendChild(script);
}

특정 ID로 스크립트 태그를 만든 다음 해당 ID가 있는지 확인 하시겠습니까?

또는 스크립트 'src'를 검사하는 스크립트 태그를 반복하고 피하려는 것과 동일한 값으로 이미로드되지 않았는지 확인하십시오.

편집 : 코드 예제가 유용 할 것이라는 피드백을 따르십시오.

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts       = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    if(scripts.length){
        for(var scriptIndex in scripts) {
            if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
                alreadyLoaded = true;
            }
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

댓글 ( https://stackoverflow.com/users/1358777/alwin-kesler ) 에서 언급했듯이 , 이것은 대안이 될 수 있습니다 (벤치 마크되지 않음).

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var alreadyLoaded = false;

    for(var scriptIndex in document.scripts) {
        if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
            alreadyLoaded = true;
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :

if(!$("body").data("google-map"))
    {
        console.log("no js");

        $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
            $("body").data("google-map",true);

            },function(){
                alert("error while loading script");
            });
        }
    }
    else
    {
        console.log("js already loaded");
    }

Merging several answers from above into an easy to use function

function GetScriptIfNotLoaded(scriptLocationAndName)
{
  var len = $('script[src*="' + scriptLocationAndName +'"]').length;

  //script already loaded!
  if (len > 0)
      return;

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptLocationAndName;
  head.appendChild(script);
}

I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again. It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.

window.addEventListener('error', function(e) {
  if (e.target.nodeName === 'SCRIPT') {
    var scriptTag = document.createElement('script');
    scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
    document.head.appendChild(scriptTag);
  }
}, true);

Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:

function check_script_loaded(glob_var) {
    if(typeof(glob_var) !== 'undefined') {
    // do your thing
    } else {
    setTimeout(function() {
    check_script_loaded(glob_var)
    }, 100)
    }
}

Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.

Key points for me were

  • add an #id tag, so it's easy to find, and not duplicate
  • Use .onload() to wait until the script has finished loading before using it

    mounted() {
      // First check if the script already exists on the dom
      // by searching for an id
      let id = 'googleMaps'
      if(document.getElementById(id) === null) {
        let script = document.createElement('script')
        script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
        script.setAttribute('id', id)
        document.body.appendChild(script) 
    
        // now wait for it to load...
        script.onload = () => {
            // script has loaded, you can now use it safely
            alert('thank me later')
            // ... do something with the newly loaded script
        }      
      }
    }
    

참고URL : https://stackoverflow.com/questions/9521298/verify-external-script-is-loaded

반응형