Подтвердить что ты не робот

Проверьте, загружен ли jquery, затем загрузите его, если false

Кто-нибудь знает, как проверить, загружен ли jquery (с javascript), затем загрузите его, если он не был загружен.

что-то вроде

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

Ответ 1

Возможно, что-то вроде этого:

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

Ответ 2

Избегайте использования "if (! jQuery)", поскольку IE вернет ошибку: jQuery - это "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, которое медленнее, если на странице есть изображения. Здесь образец script, который проверяет, загружен ли файл JQuery, поскольку у вас не будет удобства использования $(document).ready(function...

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

Ответ 3

Способ 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);
}

Ответ 4

Попробуйте следующее:

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

Это проверяет, доступен ли jQuery или нет, если он не добавит динамически из указанного пути.

Ссылка: Имитировать "include_once" для jQuery

ИЛИ

include_once эквивалент для js. Ссылка: 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;
}

Ответ 5

Даже если у вас может быть приложение для добавления главы, оно может не работать во всех браузерах. Это был единственный метод, который, как я нашел, работает последовательно.

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

Ответ 6

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

Ответ 7

Я использую 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 и выполнил код. Его сломанный и он никогда не включался, если цикл typeof jQuery подходит как функция вместо undefined.

Это из-за кэшированной старой версии jquery 1.6.1, которая возвращает функцию и разбивает мой код, потому что я использую jquery 1.9.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>