当然,该方法不局限于jQuery的检测,对与任何Javascript变量或函数都是通用的。

当前网页加载jQuery后,jQuery()或$()函数将会被定义,所以检测jQuery是否已经加载存在以下2种方法:

方法1:

if (jQuery) { 
// jQuery 已加载 
} else { 
// jQuery 未加载 
} 

方法2:

if (typeof jQuery == 'undefined') { 
// jQuery 未加载 
} else { 
// jQuery 已加载 
} 

备注:
以上我们通过检测jQuery函数是否已定义,这是一个比较安全可靠的方法,因为当你加载jQuery.js后,可能会再加载prototype.js或mootools.js等,其中可能会重定义$()函数, 检测$()函数是否存在将会不准确。

平时我们加载jquery,如果带宽与速度不是很好的情况可以考虑引用第三方的jquery

<script src="//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,微软等国外的,容易被强国内访问不如国内的快。

以上就是【检测jQuery.js是否已加载的判断代码】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论