greenh greenh - 1 month ago 8x
CSS Question

JS manipulation on CSS and how it result on page rendering

I know from many sources that applying CSS after the page has loaded can cause "flashing" effect - means the page will re-render the CSS.

For example:

<link rel="stylesheet"... />

However, I can't find any source for applying CSS(not inline) with JS after the page is loaded and how it's reflected by the re-rendering it self.

For example:


<link rel="stylesheet" href="style.css" type="text/css" media="all" />
<div id="divid" class="displaynone"></div>
function showit(){
document.getElementById("divid").className += " displayblock";}
window.onload = showit;


.displaynone {display:none;}
.displayblock {display:block;}

Will the second example will be forced to re-render the css after the page is loaded? I want to understand the deeps of how the
is actually apply to the


If you apply your <link rel="stylesheet"... /> after your DOM elements in your markup you can end up with "flickering" effects. This is caused because when the browser load the CSS file (a network request is made), the DOM is being already displayed in the ViewPort (which has not yet any style applied).

In the second case where you add <link rel="stylesheet"... /> in your head, the browser download your CSS file before rendering the DOM on the ViewPort. At this point your JavaScript change class attribute to the DOM and you have no flickering (as all CSS has been already loaded).

When you change the DOM with a property which is related to the its visual representation the browser execute a "paint" this means that an area of the ViewPort is partially or fully re-rendered.

An interesting article regarding browser painting and performance and rendering path. Also of interest if you are using Chrome Dev Tools.