EN VI

How to avoid flicker when a page first loads due to CSS styles changing via JavaScript?

2024-03-14 17:30:05
How to avoid flicker when a page first loads due to CSS styles changing via JavaScript

I' having a little trouble between load order of my CSS and JavaScript.

Basically, what is happening, is that I have a div with blue background, and my css applies a "cut" on it, slicing it diagonally. When the page first loads (or when CTRL+SHIFT+R), the "cut" is not there for a very short but noticeable duration, and then appears after the JavaScript loads.

I have this CSS

.banner-bottom-fx 
{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 0;
    border-top: 0 solid transparent; /* changes via JavaScript */
    border-right: 0 solid white; /* changes via JavaScript */
}

Where border-top and border-right values change via this JavaScript

function UpdateBannerFx()
{
    const banner = document.querySelector('.banner-bottom-fx');

    const borderRightWidth = window.innerWidth;
    const borderTopWidth = borderRightWidth / 30;

    banner.style.borderRightWidth = borderRightWidth + 'px';
    banner.style.borderTopWidth = borderTopWidth + 'px';
}

document.addEventListener("DOMContentLoaded", function() 
{
    UpdateBannerFx();
    // Update border widths when window is resized
    window.addEventListener('resize', UpdateBannerFx);
});

I know the "flicker" is due to my CSS styles.css, which loads in my header, and then the JavaScript which loads from main.js in the footer. Is there any way to prevent said flicker?

Solution:

You don't need JavaScript for this. 100vw is equivalent to window.innerWidth.

.banner-bottom-fx {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 0;
    border-top: calc(100vw / 30) solid transparent; /* window.innerWidth / 30 */
    border-right: 100vw solid white;  /* window.innerWidth */
}

See CSS Values and Units

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login