Prioritizing the Loading of CSS Over Javascript

I have created a custom navbar/menu. Currently, it is loading CSS from my style.css and the JS is included in the PHP file using the following setup:

<link rel="stylesheet" href="style.css" type="text/css">
 <nav> ... </nav>
 <script>
$(function () {
        $('.toggle-menu').click(function (){
        $('.exo-menu').toggleClass('display');

        });
    });
    jQuery(document).ready( function ( $ ){
        $(".change>a").hover( function () { 
            $(this)[0].click();
        }, 
        function () {
        /* code for mouseout */
    });
    });
</script>

The internal JS seems to be causing issues with the CSS loading.

Is there a way I can ensure that the called CSS loads before the JS while maintaining the current setup, without moving the Javascript to a separate .js file?

So far, I have attempted:

<head>
   <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body onload="initNavigation()">
    <nav> ... </nav>
    <script>
        function initNavigation() {
            $(function () {
                $('.toggle-menu').click(function (){
                $('.exo-menu').toggleClass('display');
                });
            });
            jQuery(document).ready( function ( $ ){
                $(".change>a").hover( function () { 
                $(this)[0].click();
                }, 
                function () {
                /* code for mouseout */
                });
            });
        }
    </script>
</body/>

and

<head>
   <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
    <nav> ... </nav>
    <script>
        window.onload=function(){
            $(function () {
                $('.toggle-menu').click(function (){
                $('.exo-menu').toggleClass('display');
                });
            });
            jQuery(document).ready( function ( $ ){
                $(".change>a").hover( function () { 
                $(this)[0].click();
                }, 
                function () {
                /* code for mouseout */
                });
            });
        }
    </script>
</body/>

Can someone point out where I might have made a mistake? I'm thinking it could be related to the .ready part, but if so, I'm unsure how to address it without impacting the functionality of the JS.

Would changing the position of the JS to the head section below the CSS make a difference?

Answer №1

To ensure your JavaScript code runs properly, you can utilize the onload event in the body tag and encapsulate your JS within a function.

<head>
  <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body onload="initNavigation()">

  <nav></nav>

  <script>
    function initNavigation() {
      // place your script here
    }
  </script>
</body>

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

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

In the realm of JavaScript with Express and Mongoose, it is important to ensure that all promises from Mongoose are executed

Currently, I am developing a forum API where each forum can have multiple threads, each thread can have multiple posts, and each post may have many replies. To establish these relationships, I have defined the schema as follows: var PostSchema = new Sche ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

The overlay lingers on the page even after the modal successfully redirects to the search

My goal is to implement a modal that prompts users to input their search term and find recipes with a specific ingredient. I have successfully achieved this by using simple redirection. However, upon redirecting to the search results, the overlay remains o ...

Unveiling the method to retrieve AuthErrorCode from Firebase JS SDK without the need for the auth/ prefix

I'm curious about how to retrieve the correct error code in Firebase v10. public resetPassword(email: string, actionCodeSettings: ActionCodeSettings): Promise<void> { return sendPasswordResetEmail(this.auth, email, actionCodeSettings); } publ ...

Using Regular Expression in JavaScript to replace variables within a string

Looking for assistance to replace keywords in a string with pre-defined variables. Currently, the code only displays variable names instead of their content. Can anyone provide help? Desired Output: 1111Test1 2222Test2 3333Test3 Current Output ...

Using AJAX to dynamically load an image by setting the image path as the source of the image tag

I'm facing a challenge with my AJAX call that is used to display user details in a modal. I recently integrated an image upload feature for users, but now I'm struggling to display the uploaded image. I have tried looking for solutions online, bu ...

Guide on automatically logging in to a specific website using Selenium with Kakao, Google, or Naver credentials

I encountered an issue with my selenium login code for a particular website, where the keys seem to be generating errors. https://i.stack.imgur.com/wJ3Nw.png Upon clicking each button, it brings up the login tab. However, I keep encountering this error ...

Dynamically apply colors to the pagination arrows to enhance visual appeal

Looking to incorporate the 4 standard arrows for pagination with dynamic coloring. Any advice on how to achieve this? Thanks, Javier ...

Ensure that an async function's result is resolved before rendering react routes

I've been working on setting up an authentication service in my single-page application using React in the routes file. The goal is to check if a user is trying to access a private path, and verify that the token stored locally is valid. However, I&ap ...

Jquery validation is ineffective when it fails to validate

I have implemented real-time jQuery validation for names. It functions correctly in real-time, however, when I attempt to submit the form, it still submits the value even after displaying an error message. Below is the code snippet for the validation: $ ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...

Difficulty in accurately retrieving the value in a PHP echo statement using jQuery

$id = "123"; When on the page book.php, $id is passed to an external jquery-book.php file. <script type="text/javascript"> var id = '<?php echo $id; ?>'; </script> <script type="text/javascript" src="jquery-book.php"& ...

How to style tags between select options in HTML using React JS?

Is there a way to customize the appearance of a span element that is nested within an option tag? <select> <option value="option1">Active Wallet <span style={{fontWeight:'bold!important'}}>mBTC</span></o ...

When adjusting the top margin of the main content in CSS, the fixed top navigation section's margin also decreases simultaneously with the main content

I am in the process of creating a basic static blog page using HTML5, SASS, and CSS. While working on the design, I utilized the 'nav' semantic element for a fixed top bar on the page that remains visible even when scrolling down. Additionally, ...

What is the reason behind the one-way functionality of underscore's difference method?

If I asked you, "What separates these two arrays: ['a'] and ['a', 'b']?" your answer would be 'b', correct? I'm curious why underscore doesn't automatically provide bidirectional diff functionality. How ca ...

Add a div to another div when a droppable element is dropped, ensuring it only happens once

I have a draggable feature that, when dropped onto the target area, adds a delete button dynamically: $( "#committed" ).droppable({ hoverClass: 'drophover', drop: function( event, ui ) { ...

What is the best way to utilize a WMS tile layer provided by GeoServer with the help of Vuelayers?

I am in the process of creating a web mapping application using the Vue Layers library, which is described as "Web map Vue components with the power of OpenLayers". Within my template, I have the following code: <vl-map @singleclick="hideOverlay" @pos ...