verifique se jquery foi carregado e carregue-o se for falso


117

Alguém sabe verificar se o jquery foi carregado (com javascript) e depois carregue-o se ainda não foi carregado.

algo como

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

1
obrigado pelo aviso! com sorte, nunca terá de ser chamado. apenas tentando adicionar um pouco de redundância
— dezessete de

Respostas:


166

Talvez algo assim:

<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
Observe que isso pressupõe que o documento tem um headelemento de script ao qual pode anexar
— Daniel LeCheminant

1
@DanielLeCheminant bom ponto sobre isso. E se fosse( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
— pawelglow

3
@Pawel Eu vi algumas implementações inserirem o elemento antes / depois da primeira tag de script, já que você sabe que deve haver um desses.
— Daniel LeCheminant

Acredito que anexar uma tag de script ao corpo funciona em todos os navegadores.
— Steven Lu

3
Portanto, em conclusão; o método mais seguro será: (document.getElementsByTagName ('head') [0] || document.getElementsByTagName ('script') [0]) .appendChild (script); Uma vez que haverá pelo menos uma instância da tag de script.
— tormuto

106

Evite usar "if (! JQuery)", pois o IE retornará o erro: jQuery é 'indefinido'

Em vez disso, use: 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>

Você também precisará verificar se o JQuery foi carregado após anexá-lo ao cabeçalho. Caso contrário, você terá que esperar pelo evento window.onload, que é mais lento se a página tiver imagens. Aqui está um script de amostra que verifica se o arquivo JQuery foi carregado, já que você não terá a conveniência de poder usar $ (document) .ready (function ...

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


Sobre o quê script.onload = function() { alert('jQuery loaded!'); }? Isso funcionaria?
— roubo de

14

Método 1:

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

Método 2:

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

Se o arquivo jquery.js não estiver carregado, podemos forçar o carregamento assim:

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

Experimente isto:

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

Isso verifica se o jQuery está disponível ou não, caso contrário, ele adicionará um dinamicamente do caminho especificado.

Ref: Simule um "include_once" para jQuery

OU

equivalente include_once para js. Ref: 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

Mesmo que você tenha um cabeçalho anexando, ele pode não funcionar em todos os navegadores. Esse foi o único método que descobri funcionar de maneira consistente.

<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
Não é document.write ALTAMENTE desaprovado?
— Carcigenicar-se em

1

Você pode verificar se o jQuery está carregado ou não de várias maneiras, como:

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
}

Agora, depois de verificar se o jQuery não está carregado, você pode carregar o jQuery assim:

Embora esta parte tenha sido respondida por muitos neste post, mas ainda respondendo por uma questão de integridade do código


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

Post antigo mas fiz uma boa solução o que é testado em locais servais.

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

CÓDIGO:

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

No GitHub há uma explicação melhor, mas geralmente essa função você pode adicionar em qualquer lugar no seu código HTML e inicializar o jquery se ainda não estiver carregado.


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

você tem que adicionar algum comentário em seu código para explicá-lo.
— 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

Estou usando o CDN para meu projeto e, como parte do tratamento de fallback, estava usando o código abaixo,

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

Apenas para verificar, removi a referência CDN e executei o código. Ele está quebrado e nunca entrou em se o loop como tipo de jQuery está vindo como função em vez de indefinido.

Isso ocorre por causa da versão mais antiga em cache do jquery 1.6.1 que retorna a função e quebra meu código porque estou usando o jquery 1.9.1. Como preciso da versão exata do jquery, modifiquei o código conforme abaixo,

<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>
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.