2009-12-01 12 views
107

¿Alguien sabe cómo comprobar si se ha cargado jquery (con javascript) y luego cargarlo si no se ha cargado?compruebe si se ha cargado jquery, y luego cárguelo si es falso

algo así como

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

Antes de hacer esto tarde -carga de la marca jQuery Asegúrese de tomar nota de este informe de errores: http://dev.jquery.com/ticket/4196 –

+1

¡gracias por el aviso! con suerte nunca tendrá que ser llamado. simplemente tratando de agregar un poco de redundancia – seventeen

+0

Gracias por la sugerencia – Patriotec

Respuesta

142

Tal vez algo como esto:

<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

Tenga en cuenta que esto supone que el documento tiene una 'cabeza 'que puede agregar un elemento script a –

+1

@DanielLeCheminant buen punto sobre eso. ¿Qué pasaría si fuera '(document.getElementsByTagName ('head') [0] || document.getElementsByTagName ('body') [0]) .appendChild (script);' – pppglowacki

+3

@Pawel He visto algunas implementaciones insertar el elemento antes/después de la primera etiqueta de secuencia de comandos, ya que sabes que tiene que haber una de esas. –

103

Evitar el uso de "si (jQuery!)", Ya que IE devolverá el error: jQuery es 'indefinido'

En su lugar 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> 

También deberá comprobar si el archivo JQuery se ha cargado después de agregarlo al encabezado. De lo contrario, tendrá que esperar el evento window.onload, que es más lento si la página tiene imágenes. Aquí hay un script de ejemplo que comprueba si el archivo se ha cargado jQuery, ya que no tendrá la comodidad de poder utilizar $ (document) ready (función ...

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

+0

¿Qué pasa con 'script.onload = function() {alert ('jQuery loaded!'); } '? Funcionaría eso? – robsch

7

Prueba esto:

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

Esto comprueba si jQuery está disponible o no, si no se va a añadir una dinámica a partir de ruta especificada

Ref:. Simulate an "include_once" for jQuery

O

include_once equivalent for 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

A pesar de que puede tener una cabeza añadiendo puede que no funcione en todos los navegadores. Este fue el único método que encontré para trabajar consistentemente.

<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

¿No está 'document.write' * ALTAMENTE * mal visto? – Carcigenicate

11

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 
} 

Si el archivo jquery.js no está cargado, se puede forzar la carga que de este 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); 
} 
-1

Estoy usando CDN para mi proyecto y como parte de Handle de reserva ing, yo estaba usando a continuación el código,

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

Sólo para verificar, quité referencia CDN y ejecutar el código. Está roto y nunca se ingresó si el bucle como tipo de jQuery viene como función en lugar de indefinido.

Esto se debe a la versión anterior en caché de jquery 1.6.1 que devuelve la función y rompe mi código porque estoy usando jquery 1.9.1.Como necesito versión exacta de jQuery, he modificado el código de la siguiente manera,

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

tiene que agregar algún comentario sobre su código para explicarlo. –

0

Puede comprobar si jQuery se carga o no por muchas maneras, tales 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 
} 

Ahora después de comprobar si jQuery no está cargado, puede cargar jQuery así:

Although this part has been answered by many in this post but still answering for the sake of completeness of the code


// 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); 
Cuestiones relacionadas