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


117

누구든지 jquery가 (자바 스크립트로)로드되었는지 확인한 다음로드되지 않은 경우로드하는 방법을 알고 있습니까?

뭔가

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

1
고마워요! 실제로 호출 할 필요가 없을 것입니다. 약간의 중복성을 추가하려고합니다
17

답변:


166

아마도 다음과 같습니다.

<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>

5
문서 head에 스크립트 요소를 추가 할 수
있는가

1
@DanielLeCheminant 좋은 지적입니다. 그것이 경우 어떻게( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
pawelglow

3
@Pawel 일부 구현에서 첫 번째 스크립트 태그 앞 / 뒤에 요소를 삽입하는 것을 보았습니다. 그 중 하나가 있어야한다는 것을 알고 있기 때문입니다.
Daniel LeCheminant 2012

본문에 스크립트 태그를 추가하면 모든 브라우저에서 작동한다고 생각합니다.
Steven Lu

3
그래서 결론적으로; 가장 안전한 방법은 다음과 같습니다. (document.getElementsByTagName ( 'head') [0] || document.getElementsByTagName ( 'script') [0]) .appendChild (script); 최소한 스크립트 태그의 인스턴스가 있기 때문입니다.
tormuto

106

IE에서 오류를 반환하므로 "if (! jQuery)"사용을 피하십시오 : jQuery is 'undefined'

대신 사용하십시오 : if (typeof jQuery == 'undefined')

<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 파일이로드되었는지 확인하는 샘플 스크립트입니다. $ (document) .ready (function ...

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


어때 script.onload = function() { alert('jQuery loaded!'); }? 작동할까요?
robsch

14

방법 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);
}

8

이 시도 :

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

이것은 jQuery를 사용할 수 있는지 여부를 확인하고 그렇지 않은 경우 지정된 경로에서 동적으로 추가합니다.

참조 : jQuery에 대한 "include_once"시뮬레이션

또는

js에 해당하는 include_once. 참조 : 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;
}

2

머리를 추가해도 모든 브라우저에서 작동하지 않을 수 있습니다. 이것이 제가 일관되게 작동하는 유일한 방법이었습니다.

<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>

2
크게 눈살을 찌푸 document.write 리지 않습니까?
Carcigenicate 2015

1

다음과 같은 여러 방법으로 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);

1

이전 게시물이지만 serval 장소에서 테스트되는 좋은 솔루션을 만들었습니다.

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를 초기화합니다.


0
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();

설명하려면 코드에 주석을 추가해야합니다.
Ebrahim Poursadeqi

0
<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>

-1

내 프로젝트에 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 가 undefined 대신 함수 로 오는 형태 로 if 루프에 들어 가지 않습니다.

이것은 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>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.