Utilizing jQuery to dynamically load CSS files on a webpage

For my website, I have implemented 4 different .css files to handle various screen resolutions.

Here is the innovative jquery code I've developed to dynamically load these files based on the width of the screen.

<link id="size-stylesheet" rel="stylesheet" type="text/css" href="public/_css/normal.css" />

<script language="javascript" type="text/javascript">
function adjustStyle(width) 
{
    width = parseInt(width);
    if(width >= 1920) 
    {
        $("#size-stylesheet").attr("href", "public/_css/bigger.css");
    }
    else if (width >= 1600) 
    {
        $("#size-stylesheet").attr("href", "public/_css/big.css");
    }
    else if (width >= 1366) 
    {
        $("#size-stylesheet").attr("href", "public/_css/normal.css");
    }
    else 
    {
        $("#size-stylesheet").attr("href", "public/_css/small.css");
    }
}

$(function() 
{
    adjustStyle($(this).width());

    $(window).resize(function() 
    {
        adjustStyle($(this).width());
    });
});
</script>

While testing the page in Chrome, I noticed that whenever I resize the window, it flickers excessively. On the contrary, it functions seamlessly on IE8 and Firefox.

You can view a live example of this page by visiting: testing page

I suspect that each time the window is resized, the css files are being reloaded repeatedly, causing the flickering issue. Is there a way to preload the css files for quicker loading during window resizing?

Answer №1

The inconsistent behavior you're seeing is likely due to the browser not handling intensive computations well during the window.onresize event. With this event potentially firing multiple times per second, it can easily lead to a backlog of AJAX requests overwhelming the system.

To address this issue, I suggest utilizing media queries for a more efficient solution. Additionally, considering your openness to Javascript, incorporating a CSS3 media query polyfill for IE6-8 could prove beneficial in achieving desired responsiveness across various browsers.

This approach not only ensures better compatibility moving forward but also simplifies the process of phasing out support for older browsers by discontinuing the use of the polyfill when necessary, rather than reworking CSS entirely from scratch.

Answer №2

Consider enhancing the existing conditions in the if statement:

if(width >= 1920 && !$("#size-stylesheet").attr("href") === "public/_css/bigger.css") 
    {
        $("#size-stylesheet").attr("href", "public/_css/bigger.css");
    }
    else if (width >= 1600 && !$("#size-stylesheet").attr("href") === "public/_css/big.css") 
    {
        $("#size-stylesheet").attr("href", "public/_css/big.css");
    }
    ...

This approach ensures that the CSS is only replaced once, rather than being updated every time a resize event occurs.

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

Fluidity in CSS Video

I'm currently working on developing a dynamic video display component for my personal portfolio website. The main concept involves showcasing a mobile application video placed on top of a phone mockup within a designated container. My challenge lies ...

Creating a string of DIV elements with PHP and mySQL - is it possible?

I am in the process of creating a well-formatted product list using data from an SQL database. The goal is to have my website display a store layout with small boxes containing brief information about each product that, when clicked, will open up detailed ...

How can I ensure that the form submit event is delayed until the onChange event is completed when using jQuery?

Imagine a scenario where a textbox on a webpage has a 'change' event attached to it using jQuery. $('.myFormClass').on('change', '.amount', function () { // An AJAX call is made here, and the respons ...

If the blank option is chosen, then proceed to select option 3

Appreciate any assistance on this matter. In our dropdown menu, there is an empty option at the top. <select id="Flags"> <option></option> <option value="Corporate">Corporate.png</option> <option value="Store2">Store2 ...

jQuery does not have the capability to add or remove classes

I am currently using Vue.js within Laravel, and in the watch action, I am utilizing jQuery. I am puzzled as to why hasClass is functioning correctly, but addClass, removeClass, and toggleClass are not working as expected. Here is a snippet of my HTML cod ...

What is the best way to create this using html and css?

Struggling to recreate a design I was given: I currently have this setup: How can I insert vertical lines spanning the full height between the options? <ul id="navigation"> <li><a href="#">Log In</a></li> <li> ...

What are the alternative ways to deploy a React app on Node.js without relying on Express?

Is there a way to achieve serving html files without using Express in Nodejs? I have experience with serving html files through http/https in a typical website without a frontend framework, but when attempting to do the same with index.html from a React ap ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Interacting with PHP variables in JSON format

I've recently started using JSON to exchange data between pages, but I am facing a challenge that I can't seem to solve. Essentially, my issue lies in one page where I am utilizing jquery's getJSON method to retrieve JSON data from another ...

Unable to locate the element within the dataset

Here is the JavaScript code I am currently using: $.ajax({ type: 'POST', url: url, data: {id: id, 'YII_CSRF_TOKEN': token }, success: function(data) { var content = $(data).find('.content'); co ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

The printing function for the window system can cause disruptions to the layout of the table

After creating a page with a simple table that can be filled in and printed, I noticed some issues with the table formatting after printing. The intended table design was supposed to look like this: https://i.stack.imgur.com/aAk89.png However, upon print ...

Elaborate on the specific error message within the .error() jQuery function

Currently, I am utilizing .error() as the callback for .post(). Here is an example of how I am using it: $.post("url", function(data){}) .error(function(){ alert("some error"); }); If an error occurs, I would like to display a detailed error ...

Calculating the total number of records in a MySQL database using PHP can be achieved by

I need help with counting all rows in a dataset and displaying the number as part of a small statistic later on. Currently, I'm facing an issue where my PHP code is not returning the correct number of rows. The HTML echo works fine when displaying te ...

Looking for assistance with CSS positioning techniques

Creating a dropdown list with a caret icon for each item is my goal, but I'm facing some challenges. Here's the code snippet of the div structure: <div class="class-to-div1" id="{{ div.id }}" data-cardsnum="{{ div.num }}"> <div clas ...

Enhancing websites with font-awesome icons and upgrading from older versions to the latest

Seeking guidance on updating our project to use the latest Macadmine theme. The transition from Font Awesome 3 to Font Awesome 4 requires changing all icons to their proper names. I came across a helpful resource at https://github.com/FortAwesome/Font-Aw ...

What is the best way to create a straightforward menu for my HTML game?

I have been working on a basic HTML game and it seems to be functioning more or less. I'm wondering if it's possible to create a simple menu with an image in the background and a "click to start" button within the same file. Any suggestions or ti ...

Guide on transferring a file to Node.js using FormData and receiving a confirmation response from Node

Hello, I'm currently working on a basic form where I'm attempting to send a file to my Nodejs server using the FormData object. However, I'm facing an issue as my Node server does not seem to receive the file. Additionally, I would like to k ...