Fluctuating CSS appearance during content loading and asynchronous CSS loading

As I work on loading a new page and a CSS file for it using AJAX, I encounter an issue.

Once all the CSS files are added to the page, I set the opacity to 1, expecting the page to display with the CSS applied immediately. However, it initially appears without the CSS, and only after a short delay does the styling kick in. This delay is unattractive and I am seeking a solution to prevent it.

I have not been able to find a straightforward method to detect when the CSS has fully loaded.

Does anyone have any insight into why this is happening? My theory is that the CSS may not be completely downloaded yet, but I am unsure of how to address this issue.

Answer №1

One method to determine if a CSS file has fully loaded and applied styles is to create a fake "layout" element in your CSS file and then check for its dimensions using JavaScript.

For example, in your CSS file:

#layout{ height:1px }

Then in your JavaScript code (using jQuery in this example):

var $layout = $('<div>').attr('id', 'layout').appendTo('body');
var check = function() {
    return $layout.height() == 1;
}

if ( !check() ) {
    var tries = 0,
        interval = 10,
        timeout = 5000; // maximum time to check for CSS application
    setTimeout(function timer() {
        if ( check() ) {
            console.log('CSS file has loaded and styles applied');
            $layout.remove();
        } else if (tries*interval >= timeout) {
            console.log('Timeout reached');
        } else {
            tries++;
            setTimeout(timer, interval);
        }
    }, interval);
}

Answer №2

Uncertain about the impact on your setup, but one potential solution could be:

  • Include default CSS in the header of the page to hide any content causing the 'flicker' issue.
  • In the dynamically loaded CSS, reverse this effect to display all content.

If functioning without JS is a requirement, it's essential to factor that into your decision-making process.

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

Implement Bootstrap and CSS to ensure that my content appears below the header when users scroll down

I am struggling with a simple HTML page that is working well with CSS, but encountering an issue where the input form gets placed above the header when scrolling down. I want the header to always remain above the content even while scrolling. Any suggesti ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

How to modify CSS variables depending on the parent class: Leveraging the power of Sass and Tailwind CSS

Currently, I am in the process of customizing a Next.js website with Tailwind CSS and working on implementing a theme switching feature utilizing CSS (Sass) variables. There are two primary modes I am focusing on: Default mode: consisting of light and da ...

Tips for setting unique click functions for each face of a cube using React Three Fiber

Hey there! I have created a basic Cube component using react three fibre. import {useState,useRef} from 'react'; import { useFrame } from '@react-three/fiber'; const Box = ({props}) =>{ const ref = useRef() const [hove ...

How can one create a hidden color box?

$.colorbox({ href:"/check.html", transition:"elastic", speed: 150, innerWidth:"910", iframe:true, fastIframe:false, fixedPosition:fixedPos, onComplete:function(){ var $ ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

Can multiple objects be grouped together and easily dragged in Leaflet?

Is there a way to group a set of objects together so they can be dragged simultaneously? I want to make multiple objects draggable on a map and have them behave as a single marker when moved. Currently, I have a geojson file containing several objects that ...

The impact of adjusting the article's margin-top on the margin-top of

I want these two divs to have different positioning. The sidebar should remain fixed at the top. Why is the sidebar aligned with the article div instead of sticking to the top? body{ margin: 0; padding: 0; } div#sidebar{ background-color: yel ...

Mastering universal code creation with the composition API in Quasar

The Quasar website explains that for writing universal code, the created and beforeCreate lifecycle hooks in Vue components are executed in Server Side Rendering (SSR). This raises a question: What about setup? How can I achieve SSR functionality with th ...

Uncover the secrets of HTML with JavaScript

I'm facing an issue with extracting data from a link's data attribute and trying to decode the HTML within it, but unfortunately, it's not functioning as expected. Check out my code on JSFiddle: http://jsfiddle.net/Kd25m/1/ Here's the ...

Employing AJAX within Laravel 5 is a powerful tool to enhance dynamic

Below is the code snippet I am using for ajax: $('select[id=currency-data]').change(function () { var currency_id = $(this).val(); $.ajax({ url: "{{Route('exchange-rate')}}", type: 'POST', ...

Record AJAX replies similarly to Firebug using the C# WebBrowser component

I am looking to capture the AJAX Response of a website without waiting for the manipulated DOM Document to be fully completed. I want to capture the response similar to how it is done in the Firebug console. Thanks, Chris ...

Encountering issues while trying to duplicate react-table CodeSandbox: API error when using localhost

Trying to implement this CodeSandbox project into my own project has been challenging. On navigating to the Example component, a 404 error pops up: Error: Request failed with status code 404. The API is targeting this endpoint: http://localhost:3000/api/pr ...

Object Illumination Effect Using Three.js

Currently, I am working on creating an earth scene using Three.js and everything seems to be going well except for the large and distracting reflection disc that appears on the surface of the earth object. Does anyone have any suggestions on how to either ...

How can I transfer form data to a PHP variable using an AJAX request?

Encountering some difficulties, any insights? I have included only the necessary parts of the code. Essentially, I have an HTML form where I aim to extract the value from a field before submission, trigger an ajax call, and fill in another field. It seems ...

Transfer the HTML5 FullScreen (MAP) feature onto a separate display

I'm trying to integrate a leaflet map into my AngularJS Application, but I've hit a roadblock. My goal is to move the Fullscreen feature of the Map to a second screen (if one is available), allowing users to interact with the application on the ...

Using CSS to overlay a background image on top of a background gradient

Struggling to get both a background gradient and a background image (transparent PNG) to display in my div. No matter what, only the color gradient shows up while the image remains hidden. If I use a solid color instead of a gradient, the image displays ju ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

Require an additional button to dynamically load more content and shift all existing elements further down the page

I am looking to implement a "load more" button for an Instagram feed on my website. My current approach involves increasing the height of a specific section while moving the rest of the page down. This is what I have tried: <script> $(document.ready ...