Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reapplied by the cookie.

For example, if the canvas style is the default and a user selects the corporate style, when they open another page on the site, the canvas style briefly shows before being replaced by the corporate style. This issue is more noticeable on older computers but does occur on Chrome and other browsers for me. Is there anyone with the expertise to update the script below to first check for the cookie and then apply the default style if no cookie is found, instead of seemingly applying the default style at the same time?

The code I am currently using is as follows:

In the HTML head:

<script type="text/javascript">
$(function()
    {
        // Call stylesheet init so that all stylesheet changing functions 
        // will work.
        $.stylesheetInit();

        // This code loops through the stylesheets when you click the link with 
        // an ID of "toggler" below.
        $('#toggler').bind(
            'click',
            function(e)
            {
                $.switcher();
                return false;
            }
        );

        // When one of the styleswitch links is clicked then switch the stylesheet to
        // the one matching the value of that link's rel attribute.
        $('.styleswitch').bind(
            'click',
            function(e)
            {
                $.stylesheetSwitch(this.getAttribute('rel'));
                return false;
            }
        );
    }
);
</script>






<link rel="stylesheet" type="text/css" href="/css/canvas.css " title="canvas">
<link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">
<link rel="alternate stylesheet" type="text/css" href="/css/earth.css " title="earth">
<link rel="alternate stylesheet" type="text/css" href="/css/space-and-stars.css " title="space-and-stars">
<link rel="alternate stylesheet" type="text/css" href="/css/under-the-sea.css " title="under-the-sea">
<link rel="alternate stylesheet" type="text/css" href="/css/classical.css " title="classical">
<link rel="alternate stylesheet" type="text/css" href="/css/creative.css " title="creative">

The JavaScript part:

(function($)
    {
        // Local variables for toggle
        var availableStylesheets = [];
        var activeStylesheetIndex = 0;

        // To loop through available stylesheets
        $.switcher = function()
        {
            activeStylesheetIndex ++;
            activeStylesheetIndex %= availableStylesheets.length;
            $.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
        };

        // To switch to a specific named stylesheet
        $.stylesheetSwitch = function(styleName)
        {
            $('link[@rel*=style][title]').each(
                function(i) 
                {
                    this.disabled = true;
                    if (this.getAttribute('title') == styleName) {
                        this.disabled = false;
                        activeStylesheetIndex = i;
                    }
                }
            );
            createCookie('style', styleName, 365);
        };

        // To initialise the stylesheet with it's 
        $.stylesheetInit = function()
        {
            $('link[rel*=style][title]').each(
                function(i) 
                {
                    availableStylesheets.push(this.getAttribute('title'));
                }
            );
            var c = readCookie('style');
            if (c) {
                $.stylesheetSwitch(c);
            }
        };
    }
)(jQuery);

// Cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name)
{
    createCookie(name,"",-1);
}
// /cookie functions

Answer №1

In my opinion, the best approach would be to handle it on the server-side...

By the way, when you use

$(function()
{ 
});

jQuery will wait for the DOM to be fully loaded before executing the function.

Therefore, it is recommended to place the JavaScript code just below the <link /> tags, outside of the $(function(){}); statement. This will ensure that the script runs as soon as the browser parses it, and before the page is completely loaded (it should be positioned after the link elements because they need to be loaded first).

Answer №2

It is recommended to run your code before the DOM is ready, as waiting for jQuery's $(function(){...}) can cause flickering due to page loading delays.

For more insights, check out this link:

If you are experiencing issues with links not working, follow these debugging steps:

>>> $('link[@rel*=style][title]') --> confirms styles exist
[..., <link rel=​"alternate stylesheet" type=​"text/​css" href=​"/​css/​corporate.css " title=​"corporate">, ...]

>>> $.stylesheetSwitch('corporate') --> appears to be functioning correctly

The problem lies in the absence of onclick bindings on the links. Consider using this.getAttribute('title') instead of relying on rel="alternate stylesheet" for a unique theme identifier.

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

The inner panel height does not extend to 100% when there is overflow

When pressing the submit button on a panel containing components, an overlay appears but does not cover the entire parent panel if scrolled to the bottom. Additionally, I want the spinner to always be centered, whether scrolling or not. I've tried usi ...

What might be causing certain ajax buttons to malfunction?

There are 5 buttons displayed here and they are all functioning correctly. <button type="submit" id="submit_button1">Img1</button> <button type="submit" id="submit_button2">Img2</button> <button type="submit" id="submit_button3" ...

Styling borders of an image

I am working on an application where I have a collection of images. When the user clicks on an image, it receives a thick border around it at a certain distance. Now, I want to customize this border to reduce the spacing between the image and the border b ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

The process of creating a mind map with blank spaces included

I am working on creating a mapping system that links companies with their logos. The goal is to display these logos on a google-map. While completing the company-logo association map, I noticed that some vessel names contain white spaces, causing a compil ...

Is ajax testing with therubyracer (or execjs) worth trying out?

I'm looking to challenge myself by integrating and testing JavaScript code within a Ruby environment. My main goal is to utilize Ruby to set up the database, interact with it using my JavaScript model, and verify the JavaScript state without resorting ...

Prevent the use of the + or - symbols within the body of a regular expression when

function validateNumberInput(){ userInput = document.getElementById('txtNumber').value; var numberPlusMinusRegex = /^[\+?\-?\d]+$/g; if (userInput.match(numberPlusMinusRegex)) { alert('Vali ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

Maintained grid column stability amidst various modifications

I have a complex 2-column grid layout, and the example shown here is just one part of it. The complete code follows a similar structure. I am looking for a way to ensure that the green box always stays close to the red box in the layout, without having a ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

Tips on utilizing browser scroll for horizontal overflow of internal div?

I'm working on creating a dynamic page with a tree-like structure that easily exceeds the width of the browser window. My goal is to enable horizontal scrolling for the entire page using the browser's scrollbar, without needing a separate scrollb ...

Exploring plyr and vue.js: utilizing a computed property to fetch video duration

I am currently attempting to load content dynamically based on the duration of a video being displayed. However, I am encountering issues when trying to access the duration property. Could this problem be related to the timing of plyr's appearance wit ...

Calculating the difference between the old scrolltop and the new scrolltop in jQuery/Javascript

I have a seemingly straightforward question, yet I am struggling to find a solution. Each time a user scrolls, the scrollTop value changes. I want to subtract the previous value from the new value of the scrollTop. However, I am unsure how to store the old ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

Is it advisable to approve automatic pull requests initiated by dependabot for updating the yarn.lock file?

I've recently received some pull requests from "dependabot" in a JavaScript library I am working on, like the one found here. While I appreciate the effort to update dependencies to newer versions, it seems strange that each PR only updates the versi ...

Clearing hoverIntent using jQuery

In my scenario, I have three items identified as X, Y, and Z. The functionality of hovering is controlled by the hoverIntent. When I hover on item X, a tooltip is displayed using the following code: jQuery('.tooltiper').hoverIntent({ ove ...

Only display PHP page content if accessed through an AJAX request, not through directly typing the URL into the address bar

Is there a way to verify if a PHP page has been accessed via an Ajax request? I'm working on a page that displays a form for updating some database data (update.php), but I only want it to be accessible if it is called by a specific page named "change ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

Error: The EJS compiler encountered a SyntaxError due to an unexpected token || in the show component file located at /var/www/html

I'm currently working on a project inspired by Colt Steele's YelpCamp creation during his Udemy Web Dev Bootcamp. Everything was going smoothly until I tried to refactor some code towards the end of the course using YouTube tutorials. Now, whenev ...