當然,該方法不局限于jQuery的檢測,對與任何Javascript變量或函數(shù)都是通用的。
當前網(wǎng)頁加載jQuery后,jQuery()或$()函數(shù)將會被定義,所以檢測jQuery是否已經(jīng)加載存在以下2種方法:
方法1:
if (jQuery) { // jQuery 已加載 } else { // jQuery 未加載 } 方法2:
if (typeof jQuery == 'undefined') { // jQuery 未加載 } else { // jQuery 已加載 } 備注:
以上我們通過檢測jQuery函數(shù)是否已定義,這是一個比較安全可靠的方法,因為當你加載jQuery.js后,可能會再加載prototype.js或mootools.js等,其中可能會重定義$()函數(shù), 檢測$()函數(shù)是否存在將會不準確。
平時我們加載jquery,如果帶寬與速度不是很好的情況可以考慮引用第三方的jquery
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script><script type="text/javascript"> if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='/skin/mobile/js/jquery.min.js' type='text/javascript'%3E%3C/script%3E")); }</script>或者
<script src="http://lib.sinaapp.com/js/jquery11/1.8/jquery.min.js"></script><script>window.jQuery || document.write(unescape("%3Cscript src='/skin/mobile/js/jquery.min.js' type='text/javascript'%3E%3C/script%3E"))</script>一個是百度的,一個是新浪的,不建議使用google,微軟等國外的,容易被強國內(nèi)訪問不如國內(nèi)的快。
新聞熱點
疑難解答