Uncaught ReferenceError: $ is not defined error in HTML – Code Example

Total
0
Shares

I have this error when executing my html page, I have a normal html –

<HTML>
    <HEAD>
        <script type="text/javascript" src="js/d3.v3.min.js"></script>
        <script type="text/javascript" src="js/utilities.js"></script>
        <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
        <TITLE>Title of the page</TITLE>
    </HEAD>

    <BODY>
        This is the page body
    </BODY>
</HTML>

but when executing my page, it shows me an error in the file “utilities.js” which contains the following:

$(document).ready(function() {
    $(document).on('click','#id_article', function(e) {
            e.preventDefault();
            alert('CLICK');
            return false;
        });
});

The error is marked in the first line $(document).

Solution

The call to your scripts is incorrect, at the moment you have it like this

    <script type="text/javascript" src="js/d3.v3.min.js"></script>
    <script type="text/javascript" src="js/utilities.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>

The problem is that when the browser executes the code of utilities.js the call to JQUERY still does not occur. So it does not recognize the syntax of $. It should be like this –

    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="js/d3.v3.min.js"></script>
    <script type="text/javascript" src="js/utilities.js"></script>

Given the above, by the time the code is executed in utilities.js, the browser already knows the syntax of the JQUERY library.

You should put the scripts at the end of your page just before </body> because the scripts in the head will block the rendering of your page HTML until they are fully downloaded.

The error you have is that your libraries j3 and utilities are dependent on JQuery and each script when downloaded completely runs and continues downloading the following scripts.

You can adjust the order so that JQuery is the first to be called. When the other two libraries are executed JQuery already available.

  <head>

    <!-- downloads the script asynchronously and only stops parsing the HTML at runtime -->
    <script src="mylibraryAsync.js" async></script>

    <!-- download the script asynchronously and its execution is deferred after all the HTML is parsed -->
    <script src="mylibrary.js" defer></script>

  </head>

And even if you use async or defer, the execution order of each script must always be taken into account.

Conclusion

You get ReferenceError: $ is not defined in html when you start using $ before even loading the jquery script. The solution is to always load jquery before any script in your html file.

Leave a Reply

Your email address will not be published. Required fields are marked *