受欢迎的博客标签

Asp .Net Core Jquery调用出现ReferenceError: $ is not defined 可能存在的原因汇总

Published

一般改功能是使用了jQuery实现,如果jQuery出错,则会出现错误。

 <!--used for input radio-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js" integrity="sha512-pXR0JHbYm9+EGib6xR/w+uYs/u2V84ofPrBpkgLYyKvhZYJtUUvKSy1pgi8tJZAacsPwgf1kbhI4zwgu8OKOqA==" crossorigin="anonymous"></script>
        

 <!-- 用的jquery的radio的change事件 -->

出错原因1:

加载CDN的jQuery失败或者超时 提供jQuery的CDN出问题导致jQuery加载失败,或者由于网络问题浏览器加载jQuery文件超时,会出现jQuery未定义的错误。

<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"  asp-fallback-src="~/lib/jquery/dist/jquery.min.js"  asp-fallback-test="window.jQuery"  crossorigin="anonymous" integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk"> </script>
</environment>

解决方案: 将jQuery文件挂载在自己的网站上作为备用,如果CDN加载jQuery失败,则使用自己网站存托管的jQuery。这样的话,大部分用户依然可以通过CDN加快访问速度,而一旦CDN出问题时也可以避免出错。

  出错原因2: 加载jQuery的顺序错误

依赖于jQuery的其它JavaScript脚本先于jQuery加载完成并执行。这时jQuery尚未加载,因此依赖于jQuery的代码调用jQuery的话就会出错。

解决方案: 将jQuery库放在依赖于jQuery的JavaScript脚本之前,并且将这些代码放入document.ready来确保DOM加载完毕。

<script type="text/javascript" src="path/to/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
//依赖于jQuery的代码
});
</script>

  bootstrap4 使用 $ajax 出现错误ReferenceError: $ is not defined

jquery.slim.js与jquery有什么区别

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k.

就是去掉了ajax的功能。如果你不需要用到ajax或者使用了独立的第三方ajax库,就可以使用这个jquery.slim.js,这是个瘦身版,而不是什么插件。

In the jquery.slim.js, the following function of code are removed from jquery.js :

jQuery.fn.extend

jquery.fn.load jquery.each

// Attach a bunch of functions for handling common AJAX events jQuery.expr.filters.animated ajax settings like

jQuery.ajaxSettings.xhr,

jQuery.ajaxPrefilter,

jQuery.ajaxSetup,

jQuery.ajaxPrefilter,

jQuery.ajaxTransport,

jQuery.ajax

Setup xml parsing like jQuery.parseXML, animation effects like jQuery.easing, jQuery.Animation, jQuery.speed Therefore, change this line:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"

to:

<script src="https://code.jquery.com/jquery-3.2.1.min.js">

</script>

Bootstrap 4 Modal with JQuery and AJAX?What are the differences between normal and slim package of jquery?  .