2

I have a simple code that first loads jQuery then a script that uses the $ syntax. But I always get

ReferenceError: $ is not defined

First I thought it was because the async attribute on the script tag was set to async, but it doesn't make a difference.

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

Live snippet demonstrating the problem:

<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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71

2 Answers2

4

To clarify why removing the async attribute works, it's a boolean attribute, and, per the 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.

So async=false, where async is a boolean attribute, still means that the boolean attribute is truthy, since the attribute exists. Whatever is contained in the attribute doesn't really matter, but to avoid confusion, if it has a value at all, the value should be either the name of the attribute or the empty string.

MDN's documentation on this is misleading. Fixed, thanks Andrew-Cotterell. The only way to actually make async to be considered to be false is to make sure the attribute doesn't exist at all on the script element.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
3

Removing the async attribute on the script tag worked for me.

edit: And yes, regardless of what value assigned to async attribute, once it is present, then the script will be called asynchronously.

$(document).ready(function(){
  alert("Hello World!");
});
<script crossorigin="anonymous" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" src="https://code.jquery.com/jquery-3.4.1.js" type="application/JAVASCRIPT"></script>
Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23