What are some ways to reduce the delay of Dark mode on a website?

Can anyone help me optimize the speed at which dark mode is applied on my website? Currently, there seems to be a delay between page load and the dark mode taking effect. Below is the jQuery.js code I am using:

onload = function () {
  if (localStorage.getItem("darkMode") === "true") {
    var mode = localStorage.getItem("darkMode");
    enableDarkMode();
  }
}

function enableDarkMode() {
  $("body").addClass("dark");
  $("nav").removeClass("navbar navbar-expand-md navbar-light");
  $("nav").addClass("navbar navbar-expand-md navbar-dark");
  $('.inner-switch').text("ON");
  var mode = localStorage.setItem("darkMode", "true");
}

function disableDarkMode() {
  $("body").removeClass("dark");
  $("nav").removeClass("navbar navbar-expand-md navbar-dark");
  $("nav").addClass("navbar navbar-expand-md navbar-light");
  $('.inner-switch').text("OFF");
  var mode = localStorage.setItem("darkMode", "false");
}

$('.inner-switch').on("click", function () {
  if ($("body").hasClass("dark")) {
    disableDarkMode();
  } else {
    enableDarkMode();
  }
});

Answer №1

If you want to implement a dark mode feature, consider using a template engine like Smarty to check for dark mode before rendering the website content. With Smarty, you can assign a variable for dark mode and utilize an IF statement within the HTML of the site.

Here's an example snippet:

<body {if darkMode} dark {/if}>

This way, the website will load with dark mode already activated from the initial display.

Answer №2

It is important to understand that:

  • localStorage.getItem();
  • localStorage.setItem();

are synchronous operations that involve reading from and writing to the device's hard drive.

Due to their synchronous nature, these processes are slower compared to most other JavaScript operations. They must complete before any other tasks in the JavaScript thread can proceed.


Recommended Actions:

1) It is suggested to replace onload with onDOMContentLoaded at the beginning.

2) Additionally, consider exploring alternative methods for data persistence between pages that are faster than using webStorage:

2a) IndexedDB: This is an efficient option for storing state between pages, although it has a complex API.

2b) Cookies: A traditional method that still works, but may be excessive for this scenario.

2c) URL Query String: Using a query string in the URL can be a quick and easy client-side option compared to other methods like indexedDB or cookies.

In this case, utilizing URL Query String instead of webStorage might be beneficial.


The Future

Web developers have long awaited a solution for data persistence between pages that combines the technical advantages of IndexedDB with the simplicity of localStorage.

Google has introduced Keyword-Value Storage or KV Storage, which is currently in experimental stages. It will not be fully integrated into browsers as a built-in module until 2020 or 2021:

For more information, please refer to:

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

User-initiated closure of popup triggers error during Google sign in

After successfully implementing Google signin locally, I encountered an issue when attempting to login on a server. The error message displayed was: 'Uncaught: popup closed by user' Despite disabling adblockers and other potential interference, ...

What is the process for utilizing JavaScript to parse a JSON file stored locally?

I am trying to retrieve data from a JSON file located locally using JS/jQuery. Despite finding numerous similar questions on Stack Overflow, I have not found the right solution. All answers seem to give me a jquery.min.js:4 XMLHttpRequest cannot load file ...

Enable automatic scrolling on a website using jQuery with the option to pause

I'm trying to implement a feature in jQuery where the web page auto-scrolls to a specific point, pauses for a moment, and then continues scrolling. It's like simulating a user scrolling down a page while reading an article - stopping and starting ...

Guide for updating AjaxControlToolkit to incorporate the newest iteration of JQuery

After conducting recent penetration testing, I have been in the process of updating our code to utilize the most up-to-date version of JQuery (3.6.4). While we are awaiting another round of testing, my coworker has been using the same tool as the penetrati ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

When a <dl> element is nested within an <ol>, it will be rendered as a list format

I'm facing an issue with my CSS that affects how different browsers render definition lists embedded within ordered lists. In IE10, the list displays as expected - a bulleted list inside the ordered list without affecting the numbering. However, Firef ...

What is the best way to seamlessly integrate an image icon into a sentence, so it appears as a natural part of the text

I'm struggling to insert an (i) information icon before the phrase "Learn more" in the sentence: "Click on the 'Learn more' buttons for additional information." The icon keeps overlapping with the words "Learn more." Could someone provide s ...

Arranging SVG icons in a row within the navigation bar

Having trouble aligning the icons side by side? Even with margin and padding adjustments, I couldn't get it right. I've scoured multiple sites for a solution but couldn't find one. As an attempt to fix this, I created a bar with aligned butt ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

"Learn the process of customizing the border color of a drop-down menu using

Is there a way to add validation to a drop-down menu so that the border color turns red if an option is not selected? $("#MainContent_ddlSuppliers option:selected'").css("border", "1px solid #F78181"); ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...

Cannot add padding to the DIV element

Here is some HTML and CSS code that I've provided. .x{ border-bottom: 1px solid #000; } .y { border-bottom: 1px solid #000; } .z li{ display: inline; padding-top: 50px; } <div class="x"> <br> <br> <b ...

html form shifting positions based on screen resolution

I have been experimenting with a login screen design for my website recently. I created a form with a fixed position, but as the screen resolution changes, not only does the form's position shift, but also the image moves, causing an unwanted interse ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

Unused DIV elements in jQueryUI are identified using XSLT

Just a heads-up, I'm new to xslt so please bear with me if this seems like a silly question. In my xsl:template I have created a div element like this: <div id="objectLocked"> This object is locked by another user. Do you want to remove the lo ...

Switching class names on click in Vue.js

When clicked, I would like to toggle the class name from "product fav" to "product fav active". The change should be conditional; if the class is already active, it should be removed. ...

Error in saving webpage as HTML

I have integrated FileSaver.js into my project to enable users to save web pages as HTML. The code below is triggered when a user clicks on the download button: var originalstr=$.ajax( { type: "GET", url:"url", async: false }).resp ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

What is the method for executing a specific task using grunt.registerTask()?

My grunt tasks are registered like this - grunt.registerTask('regenerateSources', ['clean:local', 'bower', 'uglify']); When I run grunt regenerateSources, it executes the clean, bower and uglify tasks. But is there ...

Receiving an unspecified reply after making an ajax request

I am experiencing difficulties with retrieving the results from an ajax call. When I use console.log(data) to log the data, it is showing [undefined]. Here is the code snippet for the ajax call: $.get(root+'hotels/functions/ean/get-zones.php', { ...