What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below:

HTML

<select name="active_style" id="lol" class="dropdownselect" >
    <option value="default" selected="selected">Default</option>
    <option value="dark" selected="selected">Dark</option>
</select>

Javascript

$(document).ready(function() {

    var item = window.localStorage.getItem('active_style');
    $('select[name=active_style]').val(item);

    $('select[name=active_style]').change(function() {
       window.localStorage.setItem('active_style', $(this).val());
    });

    if (item == "dark") {
        $("head").append('<link rel="stylesheet" type="text/css" id="gdgt-dark" href="LINK");
    };
});

While the current setup functions properly, it has a slight drawback. Upon page load, there is a delay in loading the CSS which leads to a momentary display of the default styling to the user. Is there a more efficient way to preload the CSS before rendering the page for a quicker and smoother experience?

Your insights and assistance would be greatly appreciated.

Answer №1

Avoid utilizing jQuery in this situation as it may take longer to load. Using pure JS will result in a faster execution:

var header= document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.type= 'text/css';
newLink.rel= 'stylesheet';
newLink.href= 'style.css';
header.appendChild(newLink);

Answer №2

It seems like you've found the solution to your question about loading CSS files asynchronously.

1) One option is to utilize the loadCSSPlugin created by Filament Group. You can learn more about how to implement this plugin by checking out this article ().

2) Alternatively, if you prefer not to use the plugin, you could introduce a time delay in your loading function and display a loading icon (Modifying CSS....)

3) Another approach is to load the CSS file using AJAX. Here's a guide on how to do so (http://www.w3schools.com/jquery/jquery_ajax_load.asp). Additionally, you can perform post-processing within the success method of the ajax call ().

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

Develop a feature or method in your code that allows for the display of the specified table column based on user interaction

I'm a beginner with ASP.NET and I'd like to learn more about events and functions that will change the color of the corresponding day button when pressed: <td class="style2"> <asp:Button ID="Monday" runat="server" BackColor="#009933" He ...

Looking to incorporate nested rules in `JSS` using `CSS`?

Can someone guide me on how to use CSS class-nesting in Material-UI or JSS in general? I have been attempting the following: card: { cardHeader:{ marginTop:"30px" } } ...

Is it possible to trigger multiple button clicks using JQuery simultaneously?

Hello everyone, I am new to StackOverflow and this is my first question here. I hope it's not too silly. Thank you in advance for your help! I am trying to achieve a functionality where one button click triggers the clicks of multiple other buttons u ...

Is it possible to delete an element from an HTML form?

I'm facing an issue with removing an element from my HTML form during the loading process. The specific element in question is as follows: <input type="hidden" name="testToken" value="1000ad"></input> Here's what I've tried so ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

achieving bidirectional binding within a directive without using an isolated scope

One of my directives is set up like this: angular.module('somemodule').directive('tooltipText', function ($timeout, $compile, $document, config, $filter) { return { restrict: 'A', scope:{ tooltip: '=&ap ...

Tips for managing an event using the bxSlider callback API

I am currently using bxSlider to create a slideshow on my website. However, I now want to implement a manually controlled slideshow that also displays text content related to each image below the slideshow: Here is the code I have so far: <!--SlideSho ...

Updating the design of mui stepper icon

Is there a way to change the color of this icon from I would like it to be this color: I have tried using .Mui-disabled but it didn't work, not sure if it's .Mui-active or .Mui-completed Here is the sandbox link for reference: https://codesan ...

Navigate to items within a content block with a set height

I have a <div> that has a fixed height and overflow-y: scroll. Inside this div, there is mostly a <p> tag containing a long text with some highlighting (spans with background-color and a numbered id attribute). Just to note, this is an HTML5 a ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

Frontend experiencing issues with Laravel Echo Listener functionality

I have recently developed a new event: <?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate&bs ...

Secure verification is a critical element within the core component of React JS

Creating a user-based application using Meteor (v1.3) requires strong authentication and authorization mechanisms. I found an insightful example by the author of Flow Router that delves into setting up authentication and authorization using Flow Router. h ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

Tips for managing the submission process for dynamically generated formsORStrategies for

<tr> <form role="form" class="manualImportSubmit" action="http://localhost:5000/XXX" method="post"> <td><input name="yyy" value="FormAValue" type="hidden">TestA</td> <td><input name="before_year" class="fo ...

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

Error message: "An undefined index error occurred during an Ajax call to a

Path: homepage -> initiate ajax request to tester.php on PHP -> receive JSON data back to homepage. I am struggling to resolve this issue. Any help would be appreciated. AJAX Request: $.ajax({ url : "tester.php", type : " ...

Adjust the remaining choices according to the dropdown selection

I am looking to dynamically adjust other dropdown menus based on the selection in a specific dropdown. For example, when the main dropdown is changed to "Change," I want the other dropdowns to automatically select the "Refused to Answer" option. HTML < ...

Can PHP encode the "undefined" value using json_encode?

How can I encode a variable to have the value of undefined, like in the JavaScript keyword undefined? When I searched online, all I found were results about errors in PHP scripts due to the function json_encode being undefined. Is there a way to represent ...