controlla se jquery è stato caricato, quindi caricalo se falso


117

Qualcuno sa come controllare se jquery è stato caricato (con javascript) quindi caricarlo se non è stato caricato.

qualcosa di simile a

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

1
Grazie per il testa a testa! si spera che non debba mai essere chiamato. sto solo cercando di aggiungere un po 'di ridondanza
diciassette

Risposte:


166

Forse qualcosa del genere:

<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
Si noti che ciò presuppone che il documento abbia un headelemento di script che può aggiungere a
Daniel LeCheminant

1
@DanielLeCheminant buon punto su questo. E se fosse( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
pawelglow

3
@Pawel Ho visto alcune implementazioni inserire l'elemento prima / dopo il primo tag di script, poiché sai che deve esserci uno di quelli.
Daniel LeCheminant

Credo che l'aggiunta di un tag di script al corpo funzioni in tutti i browser.
Steven Lu

3
Quindi, in conclusione; il metodo più sicuro sarà: (document.getElementsByTagName ('head') [0] || document.getElementsByTagName ('script') [0]) .appendChild (script); Poiché ci sarà almeno un'istanza di script tag.
tormuto

106

Evita di utilizzare "if (! JQuery)" poiché IE restituirà l'errore: jQuery è 'undefined'

Usa invece: 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>

Dovrai anche controllare se JQuery è stato caricato dopo averlo aggiunto all'intestazione. Altrimenti dovrai attendere l'evento window.onload, che è più lento se la pagina ha immagini. Ecco uno script di esempio che controlla se il file JQuery è stato caricato, poiché non avrai la comodità di poter usare $ (document) .ready (function ...

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


Di cosa script.onload = function() { alert('jQuery loaded!'); }? Funzionerebbe?
robsch

14

Metodo 1:

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

Metodo 2:

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

Se il file jquery.js non è caricato, possiamo forzare il caricamento in questo modo:

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

Prova questo :

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

Questo controlla se jQuery è disponibile o meno, in caso contrario ne aggiungerà uno dinamicamente dal percorso specificato.

Ref: simula un "include_once" per jQuery

O

include_once equivalente per js. Rif: 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

Anche se potresti avere una testina aggiunta, potrebbe non funzionare in tutti i browser. Questo è stato l'unico metodo che ho trovato per funzionare in modo coerente.

<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
Non è document.write ALTAMENTE disapprovato?
Carcigenicate

1

Puoi verificare se jQuery è caricato o meno in molti modi come:

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
}

Ora, dopo aver verificato se jQuery non è caricato, puoi caricare jQuery in questo modo:

Sebbene questa parte abbia avuto risposta da molti in questo post, ma ancora rispondendo per completezza del codice


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

Vecchio post ma ho fatto una buona soluzione a ciò che viene testato sui luoghi serval.

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

CODICE:

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

Su GitHub c'è una spiegazione migliore, ma in generale questa funzione puoi aggiungere ovunque nel tuo codice HTML e inizializzerai jquery se non è già caricato.


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

devi aggiungere qualche commento al tuo codice per spiegarlo.
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

Sto usando CDN per il mio progetto e come parte della gestione del fallback, stavo usando il codice seguente,

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

Solo per verificare, ho rimosso il riferimento CDN ed eseguito il codice. È rotto e non viene mai inserito nel ciclo if come typeof jQuery viene fornito come funzione invece che indefinito.

Ciò è dovuto alla versione precedente memorizzata nella cache di jquery 1.6.1 che restituisce la funzione e interrompe il mio codice perché sto usando jquery 1.9.1. Poiché ho bisogno della versione esatta di jquery, ho modificato il codice come di seguito,

<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>
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.