JavaScript's sluggish execution in dynamic hiding of elements by their id

I have implemented a script that reads the current page's URL, checks for a specific string, and then creates a cookie with a one-day expiration. If the cookie is present, I hide four divs by their IDs using display = none. The code below is functional, but I am experiencing some slowness as the divs are briefly visible before disappearing.

I have attempted to use jQuery to hide the divs as well as the "document.getElementById .style.display = 'none';" method.

<script type="text/javascript">
var myvariab1= window.location.href;
if( myvariab1.indexOf('thetextiamsearhing') >= 0){
var date = new Date;
date.setDate(date.getDate() + 1);
var mexpire = "; expires="+date;
final_cookie = "mycookie =" + myvariab1+mexpire +"; path=/";
document.cookie = final_cookie;
}
 if (document.cookie.indexOf('mycookie') > -1 ) {
$(document).ready(function(){
$('#myid1').hide();
$('#myid2').hide();
$('#myid3').hide();
$('#myid4').hide();
});
}

</script>

How can I optimize this script for faster performance? The script is located just before the </head> tag. It is embedded within an ecommerce script that utilizes jquery.

Answer №1

A more efficient approach to hiding elements in a webpage is to dynamically create or update a style tag instead of waiting for the entire document to load. This prevents the elements from ever being displayed, improving performance. Here's an example:

var myvariab1= window.location.href;
if( myvariab1.indexOf('thetextiamsearhing') >= 0){
  var date = new Date;
  date.setDate(date.getDate() + 1);
  var mexpire = "; expires="+date;
  final_cookie = "mycookie =" + myvariab1+mexpire +"; path=/";
  document.cookie = final_cookie;
}
if (document.cookie.indexOf('mycookie') > -1 ) {
  document.head.appendChild(document.createElement('style'))
    .textContent = `
      #myid1, #myid2, #myid3, #myid4 {
        display: none;
      }
    `;
}

This method eliminates the need for heavy libraries like jQuery, resulting in faster page load times.

If there's already a style tag present in the document, you can simply add rules to it rather than creating a new one.

Answer №2

Utilize CSS to initially hide certain elements and subsequently check for the presence of cookies to determine whether to display those elements or maintain them hidden.

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

I encountered a 404 error when attempting to execute the "npm publish" command

While attempting to publish a package to the npm registry, an error is encountered after running the command npm publish. npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for buil ...

Identifying CSS on iPhone and iPad: A Guide

I need to adjust the CSS style based on different devices. This is how I currently have it set up: <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/Destop.css")" media="only screen and (min-width: 1224px)"/> <link rel="s ...

The 1and1 Server is experiencing a 500 internal error when using Ajax and jQuery .Load() functions, but accessing the URL directly seems to

Currently, I am utilizing a jQuery .load() function to enable infinite scrolling in a CakePHP web application. Below is the snippet of Javascript code: $("#post_container").append('<div class="batch row" style="display:none;"></div>&apos ...

Styling a submission button with HTML and CSS

I've tried following a few solutions on Stack Overflow, but I just can't seem to get this simple line of code to work. <a class="lp-element lp-pom-button" id="lp-pom-button-25"><span class="label" style="margin-top: -10px;">Get Notif ...

What are the steps to transform a "Next" button into a functional "Submit" button?

I am in the process of creating a multi-step form with two tabs. The first tab contains a user name input field, while the second tab contains a password input field. Upon initial page load, the first tab is visible. When I click the next button, I hide th ...

The jQuery AJAX post request is displaying an error message stating that the website xxx is not permitted by

I encountered a roadblock while attempting to use AJAX to call the eBay FindProducts API with a POST request. The error message that I got stuck on is as follows: XMLHttpRequest cannot load . Origin is not allowed by Access-Control-Allow-Origin. This ...

Showcasing JSON data on an HTML site

Having trouble displaying my JSON response on an HTML page using jQuery and AJAX. Here is my code: JSON RESPONSE { "result": [ { "list_id": "3", "state": "yuoio", "zone": null, "name": " T. Oji", "phone": "0828 ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

Change the text inside a container without losing any associated event listeners using JavaScript or jQuery

Here is the HTML code: <div id="div001"> This is ${Row.1}. <p>${Row.2} explain something else.</p> <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p> </div> My objective is ...

Express.js Res redirection problem occurring with Backbone.js due to failure in redirecting hashtag URLs

Issue Summary: Having trouble with Express.js redirect functionality. The problem occurs when trying to redirect after entering /#impulse, but works fine with /impulse/. Server processes the request for /#impulse before applying redirect checks, which re ...

Is it possible to decrease the HTML font size when making the website responsive?

I made the entire website using rem units due to utilizing the bootstrap 4 alpha version. Now, I am ready to begin the responsive design of the site. My html {font-size: 16px} declaration is set, so I am wondering if I can adjust the size of html in the m ...

How can you use console.log() effectively in an Angular application?

While debugging an Angular project, I have encountered a situation where console.log() does not seem to be working properly despite ensuring that all logging levels are enabled in the Chrome console settings. I have tried placing the console.log() statemen ...

Incorporating a button into a list item using jQuery and triggering the click event

I need assistance in adding a simple "delete button" to each item on the list. The items contain barcodes retrieved from a table, and I want to enable delete functionality for each barcode. My ideal solution involves placing an X button in the top right c ...

Issue with using an anonymous function in a jQuery settimeout call

I have implemented a script to trigger a mouseenter event for each of my DIV elements: $(document).ready(function() { $('div[id^=domainEnter]').mouseenter(function() { toggleSearchDisplay($(this).attr('domaincount'), ' ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Adjusting the size and adding ellipsis to the <td> component within a table

How can I set a fixed width for td elements in a table and use text-overflow: ellipsis to truncate the text inside the cells? I have attempted various methods without success. Can someone provide guidance on how to achieve this? <table> <tr& ...

Tips on concealing error messages and displaying only a single error message using jQuery validation

I am currently utilizing the jQuery Validate Plugin to validate my form inputs. My goal is to hide the error messages displayed next to the input fields and instead show a main error message at the bottom of the form. While I have managed to achieve this t ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

Chartist JS: line graph dipping beneath the X-axis

I am currently using the Chartist JS jQuery plugin and encountering an issue where one of the functions is extending below the x-axis even though it does not have any negative points. Is there a way to resolve this issue? Please refer to the image for bet ...

Using Mongoose to Perform Lookup with an Array as a Foreign Key

In my database, I have a collection called questions which contains fields like _id, name, and more. Additionally, there is another collection named tests with fields such as _id, name, and an array of questions. My goal is to retrieve all the questions a ...