Slower CSS rendering as Javascript finishes its tasks

I am currently dealing with a jQuery plugin that is quite large and complex, but I will not be sharing it here to keep things simple. The issue I am facing is relatively straightforward, so I will focus on the essential code snippets:

There is a click event attached to a group of buttons:

$("ul.tick-boxes button").click(function(event) {
    event.preventDefault();
    $("ul.product-grid").addClass("loading");
    $(this).toggleClass("active");
    $theElement.trigger("filterOptionsChanged");
});

If you visit this link, you can observe these buttons in action within the left sidebar:

This CSS snippet generates a checkmark when you click on the buttons:

ul.tick-boxes button.active .tick-box::after {
    content: "\e603";
    font-family: "custom-icons";
    color: #51425d;
    top: 2px;
    left: 2px;
    font-size: 0.75rem;
    position: absolute;
}

When clicking these filter options, there is a noticeable delay in my computer's rendering process for the tick-box animation. Despite the instant toggle of the 'active' class, the visual update lags until after the product grid has been manipulated. This paradoxical behavior raises the question as to why the tick-box rendering waits for the completion of the 'filterOptionsChanged' event instead of occurring simultaneously or beforehand.

Upon closer inspection using Chrome Developer Tools, I noticed that the active classes are toggling instantly upon clicking, indicating that the issue lies within the CSS rules governing the tick-mark display.

To address this problem, I experimented by preemptively displaying the tick-marks through modifying the CSS properties even before the buttons were clicked. Despite this optimization attempt, the lag persisted.

In an effort to isolate the root cause, I temporarily disabled the 'filterOptionsChanged' event trigger. Surprisingly, this led to a significant improvement in rendering speed, suggesting that the delayed activation of the tick-boxes was somehow correlated with the execution of this particular event.

Exploring alternative solutions, I delved into utilizing jQuery Deferreds to stagger the execution of the class changes and event triggering. However, this approach failed to yield the desired outcome, leaving me puzzled about the underlying cause of this rendering delay.

Answer №1

As mentioned in a Stack Overflow post, JavaScript function calls can block the user interface until they finish executing. This also applies to the original function call that triggers a click event. One way to work around this is by using a simple solution like:

setTimeout(function() { $theElement.trigger("filterOptionsChanged"); }, 200);

This setTimeout method introduces a delay before triggering the action, giving the browser enough time to refresh the UI. Adding a loading icon during the original function and removing it within the timeout period can help enhance the visual experience for users. Additionally, exploring alternatives like web workers which simulate parallel threads might be worth considering.

Answer №2

Give this a try:

CSS:

ul.tick-boxes button.active .tick-box::after {
    content: "\e603";
    font-family: "custom-icons";
    color: #51425d;
    top: 2px;
    left: 2px;
    font-size: 0.75rem;
    position: absolute;
}

JS:

    $("ul.tick-boxes button").click(function(event) {
        event.preventDefault();
        $("ul.product-grid").addClass("loading");
        $(this).toggleClass("active").fadeIn(10, function () {
            $theElement.trigger("filterOptionsChanged");
        });
    });

Utilizing callback functions to delay the triggering. Test it out and see if it meets your needs.

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 it possible to use jQuery to load an HTML file and extract its script?

I have a navigation bar with five buttons. Whenever a button is clicked, I want to dynamically load an HTML file using AJAX that includes some JavaScript code. The loaded file structure resembles the following: <div> content goes here... </div& ...

How to Make a Div Element Expand to Fill Unknown Space?

I have a box with the word "Test" inside it. I need to adjust its width to be 100% of its containing div, but I'm unsure about how to do this without using Javascript. The example in the jsFiddle linked below demonstrates what I am trying to achieve. ...

What could be causing the alteration of my JSON data when sent through a WEB.API Ajax request?

Before Ajax Call: "{ "UnitOfMeasureRelatedUnitDataInbound": [ { "Name": "test", "Active": true, "UnitOfMeasureTypeID": "dd89f0a0-59c3-49a1-a2ae-7e763da32065", "BaseUnitID": "4c835ebb-60f2-435f-a5f4-8dc311fbbca0", "BaseUnitName": null, ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Troubleshooting KuCoin API: Dealing with Invalid KC-API-SIGN Error and FAQs on Creating the Correct Signature

I want to retrieve open orders for my account using the following code snippet: import { KEY, PASSWORD, SECRET } from "./secrets.js"; import CryptoJS from "crypto-js"; const baseUrl = 'https://api.kucoin.com' const endPointOr ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

The list attribute in AngularJS seems to be malfunctioning when used in Internet Explorer 11

My current issue involves using the 'find' method within a scope. While it works perfectly fine in Chrome, there seems to be compatibility issues with Internet Explorer 11. How can I resolve this and make it work smoothly on IE 11? $scope.NameLi ...

What is the best way to create a Snap.svg map using AngularJS?

I am in the process of creating a web interface for an online board game. My goal is to load a Snap.svg map using Snap.load asynchronously. Once the map is loaded, I intend to attach a watch to a scope property and apply colors to the map based on that pr ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

What could be causing the javascript slidetoggle function to keep closing?

I have a link on a page that toggles the search form on and off. Let's say you search for Spring term classes, then you want to search for a new term and click "Start a new Search." The link works great and toggles just fine...BUT the toggle automatic ...

Failure to send serialized data via AJAX to the specified URL

After executing the SUCCESS function, I have confirmed that my values are accurate: serviceID=123&acceptAgreement=on The acceptAgreement field is an input checkbox. Despite this, the DB file does not show any updates. To troubleshoot, I attempted to ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

Get ready for 10 AM with the RxJS timer function

I am trying to figure out how to schedule a method in my code using rxjs/timer. Specifically, I want the method to run at precisely 10 AM after an initial delay of 1 minute. However, my current implementation is running every 2 minutes after a 1-minute d ...

Ways to horizontally align CSS boxes in Internet Explorer

I am facing a challenge in aligning three CSS boxes horizontally on my webpage. I attempted to achieve this by using the webkit and mozilla box orient and align properties. -webkit-box-orient:horizontal; -webkit-box-pack:center; -webkit-box-align:center; ...

Prevent the parent component's ripple effect from being activated by the child component

If I have a simple code snippet like the following: <ListItem button={true} > <Typography variant='caption' color='primary'> {value} </Typography> <Button onClick={foo} > Button ...

When implementing CSS object-fit: contain on an image, it may result in empty spaces surrounding the image

Within my image-wrapper container, I have an image with a variable resolution. The container itself has fixed dimensions for height and width. My goal is to center the image within the container both horizontally and vertically while adding a box-shadow e ...

Enlarge the image to fill the entire screen

Currently, I am working on a webpage where I am displaying data fetched from a database using Laravel framework. The code snippet is shown below: Here is how the webpage looks like - image1 What I aim to achieve is to make the div go fullscreen upon clic ...