我有一个简单的代码,首先加载 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/