欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

如何检测jquery是否已加载

程序员文章站 2022-04-05 16:17:29
...

检测jquery是否已加载的方法:1、判断【jQuery()】是否被定义,代码为【if (jQuery) { jQuery 已加载}】;2、判断【$()】是否被定义,代码为【if(typeof jQuery == 'undefined'】。

如何检测jquery是否已加载

本教程操作环境:windows7系统、jquery2.1.4版本,DELL G3电脑。

推荐:jquery视频教程

检测jquery是否已加载的方法:

当前网页加载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>

相关免费学习推荐:javascript(视频)

以上就是如何检测jquery是否已加载的详细内容,更多请关注其它相关文章!