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

What is the typical approach of JavaScript frameworks towards the 304 not-modified response?

Wondering about the inner workings of Jquery and web development in general. When a JavaScript file is requested and the server sends a 304 not-modified response, how does a framework handle it: Does it load the JS file from cache and run it? Or does it ...

suggesting options comparable to addthis or sharethis

Could you please check out ? There is a sharing box in the bottom right corner that resembles ShareThis. However, as far as I know, ShareThis does not have options for embedding or submitting content. Does anyone happen to know which plugin is being used ...

Webpage expands its reach beyond the confines of the HTML element

I've recently added a background gradient to my webpage to make it easier on the eyes, but now I've noticed that the page extends past the <html> element and continues scrolling. This also causes the background gradient to repeat below the ...

Looking to combine cells within a table using the Exceljs library

Encountered an issue while generating a worksheet in the EXCELJS library. function save_export(){ var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('sheet', { pageSetup:{paperSize: 9, orientation:' ...

Encountering an error message stating 'click' property is undefined when implementing Java Script Executor in Selenium

I encountered an issue: Cannot read property 'click' of undefined when attempting to click a button using JavaScript executor. Despite trying multiple approaches such as action classes and WebDriverWait, I have been unable to successfully click ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

designing various containers and adjusting their divisions

I have a pop-up window that contains the code snippet below, defining a template within a "container": <form method="post" class="signin" action="#"> <div id='container'> <div> <div id="divFeeTitle"&g ...

html2canvas encountered a CORS error when trying to retrieve images from an external domain

I have been attempting to export a react component as a PDF file. Here are the steps I have followed: Converting the component into an image using html2canvas Creating a PDF document Attaching the image to the PDF The component contains images with URLs ...

One approach to animating elements on a web page is by utilizing Node.js

Imagine you want to programmatically define animated movement for elements on a web page. In JavaScript, this can be achieved using techniques outlined in this helpful guide: How TO - JavaScript HTML Animations. But how would you do this in Node.js? UPDAT ...

What strategies can be employed to manage three conflicting versions of a single library within a Vite project?

I am currently facing a unique challenge in my web app development process. Specifically, I am using the Vite framework with the svelte-ts template setup to build an application that integrates different libraries for WebXR based augmented reality. The goa ...

Guide on adding an item to the end of an array with an arrow function

const appendElement = (item) => { return (list) => { }; }; Add a new item to the end of the list. Parameters item (any): The item to add. Output (Array) => Array: Generates a closure that duplicates the original list with the added ite ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

What is the best way to use CSS to hyphenate a capitalized word?

I have a single word that needs to be hyphenated, but the lang=en hyphenate: auto property does not work on capitalized words. To address this, I utilized the slice function in JavaScript to split the word in half so that the second half, which requires h ...

Tips for effectively implementing grids within bootstrap modal dialogs?

Exploring the functionality of the bootstrap-5 grid system within a modal popup has raised a puzzling issue. To investigate further, I began by incorporating the grid example into the main modal template sourced from https://getbootstrap.com/docs/5.0/compo ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation ...

Avoid automatic scrolling when moving between tabs with varying lengths in Bootstrap Tabs

I am working with a series of Bootstrap tabs that contain content of various lengths: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="home-tab" data ...

My preference is for the flex box to expand in width (sideways) without increasing in height (up and down)

Is there a way for flex items to expand in width but only in height when necessary? I enjoy using flexbox, but I find it frustrating that all flex items in a row grow to the same height even when there isn't enough content to fill them, resulting in a ...

Resetting a Material UI search filter TextField back to its initial state after clearing it

Unleashing the power of ReactJS alongside Material UI has been a journey of ups and downs for me. While I managed to create a versatile search filter component for my data tables that worked like a charm, I now find myself at a crossroads. My new goal is t ...

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...