Occasional occurrence of ReferenceError: The symbol $ is not defined

Encountering an issue with adding a background color to the nav bar upon scrolling, where it works randomly. Approximately 50% of the time, it functions correctly, and the remaining 50% results in a ReferenceError. This problem persists across various devices, browsers, and pages.

<script async src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
            $(document).ready(function() {
              $(document).scroll(function () {
                var $nav = $(".masthead");
                $nav.toggleClass('navBG', $(this).scrollTop() > $nav.height());
              });
            });
</script>
.masthead{width:100%;height:80px;position:fixed;top:0;left:0;z-index:9999;box-shadow: 0 50px 50px -20px rgba(0, 0, 0, 0.2) inset;}
.masthead.navBG{box-shadow:0 5px 30px 5px rgba(0, 0, 0, 0.4);background-color:#01417E; !important;transition:background-color 100ms linear;}
<div class="masthead">
      
    <nav id="sidenavContainer" class="sidenav">
                <!-- SOME LIs -->
                <!-- JS for Nav Functionality -->
    </nav>
        
    <div id="navTri" onclick="openNav()"><img src="menu.svg" alt="Menu" width="30"></div>
    
    <div id="logoMain"><a href="#"><img src="logo.svg" alt="Logo"></a></div>
    
</div>

The error consistently appears in the provided code snippet. Any suggestions on how to resolve this?

Answer №1

Avoid using async, it should be removed.

Check out this link for more information on async attribute

You could consider using the defer attribute instead.

Scripts with async are executed in a random order as they become available. On the other hand, scripts marked defer are executed in the order they are defined in the markup after parsing completes.

It is important to also defer your script to ensure correct execution sequence. This will prevent your script from running before jQuery loads, which can happen if you use async in this case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Energetic flair for Vue animations

I am currently developing a VueJS sidebar component. The objective is to allow the parent to define a width and display a toggle button that smoothly slides the sidebar in and out. Here is an example: <template> <div class="sidebarContainer ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Using Bootstrap to transform date format to mm/dd/yyyy

In my Django web application, I am utilizing Material Kit (Bootstrap) for the front end. My goal is to display the date on the HTML page in the format of mm/dd/yyyy. For example: 06/27/2018 The date in the database table is already stored in the forma ...

What's the best way to preserve the aspect ratio of my background image while utilizing background-size: cover;?

I have a background image that I'm working with. Is there a way to preserve the aspect ratio of the image even when using background-size: cover;? Currently, the image fits perfectly on the screen but appears slightly distorted. I've experimented ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

Including new styles in CKEDITOR.stylesSet that pertain to multiple elements

My idea involves creating a unique bullet list style with two specific features: a. A blue arrow image replacing the standard list icon b. Very subtle dotted borders above and below each list item. I am looking to incorporate this design into CKEditor t ...

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

Is there a way to efficiently line up and run several promises simultaneously while using just one callback function?

I am currently utilizing the http request library called got. This package makes handling asynchronous http connections fast and easy. However, I have encountered a challenge with got being a promisified package, which presents certain difficulties for me ...

Ensuring scope safety in jQuery AJAX requests

My intuition suggests that if I am on a laggy server and the user triggers two events quickly enough, the value of c in the success function will be based on the most recent event, potentially causing func1 to use the incorrect value. This is merely a hypo ...

the sequence in which a node executes a javascript function

Trying to update req.session.cart with new values for prod.quantity and prod.qtyCount in the shoppingCart field of order.save(). The issue is that orders are being saved with default quantity and qtyCount values, even though I'm setting cartProducts[ ...

Using the ico-moon icon in an HTML email for various email clients such as Outlook and Gmail

I would greatly appreciate it if someone could provide instructions on how to incorporate ico-moon icons into an email HTML, ensuring they can be properly displayed in various email clients such as Outlook and Gmail. ...

Is It Possible to Extract a Hidden Document Value from a Web Browser Using IWebBrowser2 in LabVIEW?

After hours of combing through the internet, I've come up empty-handed in my quest to find information related to my current project. I've created an HTML document that gathers user data and stores it in a JavaScript array. This array is then com ...

Adding a button in Node and Mongoose for updating data: A step-by-step guide

I have set up a mongoose database containing events, each event is displayed within a bootstrap card. My challenge now is to find a way to redirect the admin to a page where they can update the event card and save it to my mongoose db. The problem I' ...

Node: Nested requests within a loop

I have a complex code snippet below that sends a request to retrieve all scheduled messages before the current time. If there are any, it updates each document in the "scheduled" collection with a new date (increasing its value based on the repeat field). ...

Implementing a loading animation effect using AJAX that requires a loop delay and sleep functionality

My jquery ui dialog is loaded via ajax with a partial view from the server. Initially, the dialog opens as a dialog-ajax-loader and then animates/grows to fit the content once the call returns. The issue arises when the dialog content gets cached or the a ...

Selenium can be used to locate elements between two specific spans

I'm on a mission to locate specific text within this HTML code using Selenium <span class="value"> Receiver 1 <br> </span> Is there a way to make it more straightforward, like perhaps using span[class=value]? ...

CSS - Implementing Multi-Line Text Wrapping

Can anyone provide some guidance on how to handle an issue where having too much text in the description of an image pushes the image up? Thank you. I have created a basic fiddle - resize the window to see them inline. JSFiddle div.gallery { border: ...

Distinguishing jQuery Selectors

In the Document Object Model (DOM), there is an element written as: <div id="main" class="main"></div>. Would selecting this element by using $('#main') be different from $('.main:first')? EDIT: I should note that this ques ...