2009-12-01 41 views
107

Có ai biết làm thế nào để kiểm tra xem jquery đã được tải (với javascript) sau đó tải nó nếu nó chưa được tải.kiểm tra xem jquery đã được tải chưa, sau đó tải nó nếu sai

cái gì đó như

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

Trước khi bạn làm trễ này - tải jQuery chắc chắn bạn lưu ý báo cáo lỗi này: http://dev.jquery.com/ticket/4196 –

+1

cảm ơn những người đứng đầu! hy vọng nó sẽ không bao giờ thực sự được gọi. chỉ cần cố gắng để thêm một chút dư thừa – seventeen

+0

Cảm ơn mẹo – Patriotec

Trả lời

142

Có lẽ một cái gì đó như thế này:

<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

Lưu ý rằng điều này giả định rằng tài liệu có một 'đầu' mà nó có thể nối thêm phần tử tập lệnh vào –

+1

@DanielLeCheminant điểm tốt trên đó. Điều gì sẽ xảy ra nếu nó là '(document.getElementsByTagName ('head') [0] || document.getElementsByTagName ('body') [0]) .appendChild (script);' – pppglowacki

+3

@Pawel Tôi đã thấy một số triển khai chèn phần tử trước/sau thẻ script đầu tiên, vì bạn biết có phải là một trong số đó. –

103

Tránh sử dụng "if (jQuery!)" Kể từ IE sẽ trả lại lỗi: jQuery là 'undefined'

Thay vào đó sử dụng: 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> 

Bạn cũng sẽ cần phải kiểm tra xem JQuery đã tải sau khi gắn nó vào tiêu đề chưa. Nếu không, bạn sẽ phải đợi sự kiện window.onload, chậm hơn nếu trang có hình ảnh. Dưới đây là một kịch bản mẫu mà kiểm tra nếu tập tin JQuery đã nạp, vì bạn sẽ không có sự tiện lợi của việc có thể sử dụng $ (document) .ready (function ...

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

+0

Điều gì về 'script.onload = function() {alert ('jQuery loaded!'); } '? Liệu điều đó có hiệu quả? – robsch

7

Hãy thử điều này:

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

kiểm tra này nếu jQuery có sẵn hay không, nếu không nó sẽ thêm một động từ đường dẫn cụ thể

Ref:. Simulate an "include_once" for jQuery

HOẶC

include_once tương đương với js. Tham khảo: 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

Mặc dù bạn có thể có đầu phụ thêm nó có thể không hoạt động trên tất cả các trình duyệt. Đây là phương pháp duy nhất tôi tìm thấy để làm việc nhất quán.

<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

Không phải là 'document.write' * CAO * cau mày? – Carcigenicate

11

Phương pháp 1:

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

Cách 2:

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

Nếu tập tin jquery.js không được tải, chúng tôi có thể buộc tải nó như vậy:

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

Tôi đang sử dụng CDN cho dự án của mình và là một phần của dự phòng handl ing, tôi đã sử dụng mã bên dưới,

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

Chỉ cần xác minh, tôi đã xóa tham chiếu CDN và thực thi mã. Của nó bị hỏng và nó không bao giờ được nhập vào nếu vòng lặp như typeof jQuery là đến như chức năng thay vì không xác định.

Điều này là do phiên bản cũ hơn của jquery 1.6.1 trả về chức năng và ngắt mã của tôi vì tôi đang sử dụng jquery 1.9.1.Như tôi cần phiên bản chính xác của jquery, tôi đổi mã như dưới đây,

<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

bạn phải thêm một số nhận xét trên mã của mình để giải thích. –

0

Bạn có thể kiểm tra xem jQuery được nạp hay không bằng nhiều cách như:

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 
} 

Bây giờ sau khi kiểm tra nếu jQuery không được tải, bạn có thể tải jQuery như thế này:

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); 
Các vấn đề liên quan