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

I'm working on a CSS project and my goal is to ensure that all the items are perfectly aligned in a

I have been working on a ReactJS code and I'm struggling to achieve the desired result. Specifically, I am using Material UI tabs and I want them to be aligned in line with an icon. The goal is to have the tabs and the ArrowBackIcon in perfect alignme ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

Is it safe to use handlebars' default escaping in HTML attributes?

Currently, I am working on a project where various HTML escaping methods are being utilized. Some properties are escaped in the backend and displayed as raw strings using triple handlebars {{{escaped-in-backend}}}, while others are passed from the backend ...

Should GIT be utilized for managing version control of HTML pages?

Currently, I am developing an application that automatically generates blog pages in HTML format using JSON files. In addition to this functionality, the app also needs to support versioning for each blog created. The process involves converting JSON dat ...

referencing a fixed value within a JSP drop-down selection

My JSP contains a dropdown menu, and instead of manually inputting the values as text, I want to retrieve constants from a specific class. Here is an excerpt from my constants class called master.dao.util.MasterDataConstants //DIVISIONS FOR DROPDOWN p ...

Binding event listeners to dynamically created elements poses a challenge

I am facing difficulty in adding an event listener to dynamically created elements. The issue lies in my code where I am unable to detect the insertion of <p> element resulting in the lack of console message Bar Inserted. Could you point out if there ...

Navigation is failing to float in the correct position

Having issues with my navigation positioning, specifically when it reaches the breakpoint. There's a strange gap on the right side that I can't seem to fix by adjusting padding or margin settings. I'm relatively new to this so please bear wi ...

What could be causing the issue with Hindi text not displaying properly on Safari?

I'm having trouble with displaying Hindi text on my website. I tried pasting the text in a new file and it worked, so why is it not loading correctly in this case? The Hindi script is within the second span with the class word w2. "use strict"; le ...

How can you assign a div ID to an image with a backlink included?

I need assistance in centering an image with a back link inside a div id, positioned 850px to the left. Additionally, I require another Div Id containing text centered on the same line within that same 850px space. Below is my CSS: #container3 > div { ...

What is the proper way to showcase thumbnails in different sizes?

Currently, this is what I have: The display looks optimal with high-resolution landscape photos. This is the HTML and CSS code in use: <div class="upload-thumb ng-scope visible"> <span class="delete-media"> <span class="icon-bin ...

Bottom div refuses to adhere to the bottom of the page

I need help with creating a footer div that sticks to the bottom, left, and right of the page. The current footer doesn't extend all the way down and left. How can I resolve this without using "position: fixed;"? Below is the code snippet (I have rep ...

What's causing this error with jQuery and JSON?

When utilizing the following code snippet: - $.getJSON("admin.php?format=json", { module: "data", action: "allBusinessUnitsByClientName", clientname : $('#client').val() }, function(json) { $.each(json.items, function(i,item){ alert ...

Utilizing v-for and CSS Grid to showcase data effectively

I'm having trouble organizing my Vuex data with CSS GRID. It's turning out messy. My setup includes two columns: the first one for labels and the second for values. {{$store.state.stepOne.textfield[idx].label}} The code above is used to displa ...

How can I style <p> tags with a specific font in Tailwind Typography?

For instance, suppose I wish to utilize the markdown as shown below: # AAAAAAAAAa BBBBBBB This would then be interpreted in such a way that AAAAAAAAAa is designated as h1, BBBBBBB as <p>, and the entire content enclosed within a prose div utilizing ...

The paths of youngsters and the application of conditional styling

Here is the scenario I am dealing with: <div class="parent"> <div class"routeA"> <div class="header"> <li></li> <li class="p-highlight"></li& ...

Utilizing Jquery for JSON Data Parsing

I have some JSON data that looks like this: {"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]} In my JSP page, I&a ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Remove the float from the final list item in order to resolve display issues in Internet Explorer

I am trying to create a menu with the following HTML structure: <ul> <li id="btnHome"><a href="#">Link One</a></li> <li id="btnAbout"><a href="#">Link Two</a></li> <li id="btnContact"> ...

Activate a tooltip on the button depending on the value entered in the search field

I need to display a tooltip on the button when the search field is empty. Here is what I have attempted: // Enable hover feature const searchBtn = document.querySelector('.find__btn'); searchBtn.addEventListener('mouseover', () => ...

Collapsed Grid System

Is it possible to create a CSS grid system that meets the following requirements: The grid should have arbitrary height (with consistent width) and when a grid overflows, it should stack vertically underneath the preceding grid, regardless of other grid ...