sourcetip

jquery가 로드되었는지 확인한 후 false이면 로드합니다.

fileupload 2023. 8. 11. 22:31
반응형

jquery가 로드되었는지 확인한 후 false이면 로드합니다.

jquery가 로드되었는지(javascript로) 확인하고 로드되지 않았다면 로드하는 방법을 아는 사람?

비슷한 것

if(!jQuery) {
    //load jquery file
}

아마도 이런 것들이 있을 것입니다.

<script>
if(!window.jQuery)
{
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "path/to/jQuery";
   document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

IE에서 다음 오류를 반환하므로 "if(!jQuery)"를 사용하지 마십시오. jQuery는 '정의되지 않음'입니다.

대신 if를 사용합니다. (jQuery 유형 == 'filename')

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

JQuery를 헤더에 추가한 후 로딩했는지도 확인해야 합니다.그렇지 않으면 window.onload 이벤트를 기다려야 합니다. 이는 페이지에 이미지가 있을 경우 속도가 느립니다.$(문서)를 사용할 수 없기 때문에 JQuery 파일이 로드되었는지 확인하는 샘플 스크립트가 있습니다.ready(함수...)

http://neighborhood.org/core/sample/jquery/append-to-head.htm

방법 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

방법 2:.

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

jquery.js 파일이 로드되지 않은 경우 다음과 같이 강제로 로드할 수 있습니다.

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

사용해 보십시오.

<script>
  window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

이렇게 하면 jQuery를 사용할 수 있는지 여부를 확인하고, 사용할 수 없으면 지정된 경로에서 jQuery를 동적으로 추가합니다.

참조: jQuery의 "include_once" 시뮬레이션

OR

js에 대해 include_onece 등가입니다.참조: https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js

function include_once (filename) {
  // http://kevin.vanzonneveld.net
  // +   original by: Legaev Andrey
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Michael White (http://getsprink.com)
  // +      input by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: include
  // %        note 1: Uses global: php_js to keep track of included files (though private static variable in namespaced version)
  // *     example 1: include_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
  // *     returns 1: true
  var cur_file = {};
  cur_file[this.window.location.href] = 1;

  // BEGIN STATIC
  try { // We can't try to access on window, since it might not exist in some environments, and if we use "this.window"
    //    we risk adding another copy if different window objects are associated with the namespaced object
    php_js_shared; // Will be private static variable in namespaced version or global in non-namespaced
    //   version since we wish to share this across all instances
  } catch (e) {
    php_js_shared = {};
  }
  // END STATIC
  if (!php_js_shared.includes) {
    php_js_shared.includes = cur_file;
  }
  if (!php_js_shared.includes[filename]) {
    if (this.include(filename)) {
      return true;
    }
  } else {
    return true;
  }
  return false;
}

헤드가 추가될 수 있지만 일부 브라우저에서는 작동하지 않을 수 있습니다.이것이 제가 일관되게 작동하는 유일한 방법이었습니다.

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
  document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');        
  } 
</script>

다음과 같은 여러 가지 방법으로 jQuery가 로드되었는지 여부를 확인할 수 있습니다.

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}


if (typeof jQuery == 'function')
//or
if (typeof $== 'function')


if (jQuery) {
    // This will throw an error in STRICT MODE if jQuery is not loaded, so don't use if using strict mode
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


if( 'jQuery' in window ) {
    // Do Stuff
}

이제 jQuery가 로드되지 않았는지 확인한 후 다음과 같이 jQuery를 로드할 수 있습니다.

이 부분은 이 게시물에서 많은 사람들이 답변했지만 여전히 코드의 완전성을 위해 답변하고 있습니다.


    // This part should be inside your IF condition when you do not find jQuery loaded
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "http://code.jquery.com/jquery-3.3.1.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);

오래된 게시물이지만 여러 곳에서 테스트되는 좋은 해결책을 만들었습니다.

https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded

코드:

(function(url, position, callback){
    // default values
    url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    position = position || 0;

    // Check is jQuery exists
    if (!window.jQuery) {
        // Initialize <head>
        var head = document.getElementsByTagName('head')[0];
        // Create <script> element
        var script = document.createElement("script");
        // Append URL
        script.src = url;
        // Append type
        script.type = 'text/javascript';
        // Append script to <head>
        head.appendChild(script);
        // Move script on proper position
        head.insertBefore(script,head.childNodes[position]);

        script.onload = function(){
            if(typeof callback == 'function') {
                callback(jQuery);
            }
        };
    } else {
        if(typeof callback == 'function') {
            callback(jQuery);
        }
    }
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){ 
    console.log($);
}));

GitHub에서는 더 나은 설명이지만 일반적으로 이 기능은 HTML 코드의 아무 곳에나 추가할 수 있으며 아직 로드되지 않은 경우 jquery를 초기화합니다.

var f = ()=>{
    if (!window.jQuery) {
        var e = document.createElement('script');
        e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
        e.onload = function () {
            jQuery.noConflict();
            console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
        };
        document.head.appendChild(e);
    } else {
        console.log('jQuery ' + jQuery.fn.jquery + '');
    }
};
f();
<script>
if (typeof(jQuery) == 'undefined'){
        document.write('<scr' + 'ipt type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></scr' + 'ipt>');
}
</script>

저는 제 프로젝트를 위해 CDN을 사용하고 있으며 폴백 처리의 일환으로 아래 코드를 사용하고 있습니다.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
                if ((typeof jQuery == 'undefined')) {
                    document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));   
                }
</script>

확인을 위해 CDN 참조를 제거하고 코드를 실행합니다.jQuery 유형이 정의되지 않은 대신 기능으로 제공되는 경우 중단되고 루프에 들어가지 않습니다.

이것은 jquery 1.9.1을 사용하고 있기 때문에 함수를 반환하고 코드를 깨트리는 jquery 1.6.1의 캐시된 이전 버전 때문입니다.정확한 버전의 jquery가 필요하기 때문에 아래와 같이 코드를 수정하였습니다.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
            if ((typeof jQuery == 'undefined') || (jQuery.fn.jquery != "1.9.1")) {
                document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));   
            }
</script>

언급URL : https://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if-false

반응형