greenh
greenh

Reputation: 13

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:

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

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:

HTML:

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

CSS:

.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 displayblock is actually apply to the div.

Upvotes: 1

Views: 114

Answers (1)

GibboK
GibboK

Reputation: 73908

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.

Upvotes: 1

Related Questions