javascript - 在 jQuery 之后加载的脚本中获取 "$ is not defined"

标签 javascript jquery html

我有一个简单的代码,首先加载 jQuery,然后加载一个使用 $ 语法的脚本。但我总是得到

ReferenceError: $ is not defined

首先我认为这是因为 script 标签上的 async 属性设置为 async,但这并没有什么区别。

HTML:

<script async="false" crossorigin="anonymous" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" src="https://code.jquery.com/jquery-3.4.1.js" type="application/JAVASCRIPT"></script>

<script async="async" src="/SCRIPT/Creator/Creator.js" type="application/JAVASCRIPT"></script>

Creator.js:

$(document).ready(() => {
  function CloseModalBackground() {
    ....
  }
});

//# sourceMappingURL=Creator.js.map

演示问题的实时片段:

<script async="false" crossorigin="anonymous" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" src="https://code.jquery.com/jquery-3.4.1.js" type="application/JAVASCRIPT"></script>

<script>
// jQuery *should* be defined by now, right But no:
console.log(typeof $);
</script>

最佳答案

为了澄清为什么删除async属性有效,它是一个 bool 属性,并且根据specification :

A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

所以async=false,其中async是一个 bool 属性,仍然意味着该 bool 属性是true,因为该属性存在。属性中包含的内容并不重要,但为了避免混淆,如果它有值,则该值应该是属性的名称或空字符串。

MDN's documentation这是有误导性的。 已修复,谢谢 Andrew-Cotterell。真正使 async 被视为 false 的唯一方法是确保脚本元素上根本不存在该属性。

关于javascript - 在 jQuery 之后加载的脚本中获取 "$ is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259658/

相关文章:

javascript - JS中的数字格式?

javascript - 如何提高scrollmagic的速度

html - 在同一行 Bootstrap 中设置不同宽度的列

javascript - 如何从下拉列表中进行选择并输入文本

JavaScript 正则表达式 : Finding a String that does not contain </p>

javascript - 使用ajax和php从表中加载更多数据

JavaScript/jQuery - 性能问题

javascript - 通过调整窗口大小来缩放和维护 DIV 位置

html - 页脚元素未正确对齐

javascript - Angular CDK Overlay,更改默认覆盖容器