views:

100

answers:

4

Two part question:

  1. Do browsers have a built-in CSS interpreter like they do for JavaScript?
  2. When exactly does a browser read the CSS and when does it apply the CSS?

Specifically, I would like clarification on how or why JavaScript and CSS are different in that with JavaScript you need to specifically wait until window.onload so the interpreter can correctly getElementById. However, in CSS you can select and apply styles to classes and ids all wily nily.

(If it even matters, assume I am referring to a basic HTML page with an external stylesheet in the head)

A: 

I believe the browser interprets CSS as it finds it, with the effect that CSS in the body (inline) takes precedence over CSS (external as well) in the head

Rhys
+4  A: 

If you've worked with a slow connection anytime recently, you'll find that CSS will be applied to elements as they (slowly) appear, actually reflowing page content as the DOM structure loads. Since CSS is not a programming language, it doesn't rely on objects being available at a given time to execute properly (JavaScript), and the browser is able to simply re-assess the structure of the page as it retrieves more data by applying new styles.

Perhaps this is why, even today, the bottleneck of Mobile Safari isn't the 3G connection at all times, but it is the page rendering.

Tegeril
+4  A: 

Yes, browsers have a CSS interpreter built in. The reason you don't "wait until window.onload" is because while Javascript is a Turing-complete imperative programming language, CSS is simply a set of styling rules that the browser applies to matching elements it encounters.

Chuck
A: 

I recently bumped into this article on google page speed:

As the browser parses HTML, it constructs an internal document tree representing all the elements to be displayed. It then matches elements to styles specified in various stylesheets, according to the standard CSS cascade, inheritance, and ordering rules. In Mozilla's implementation (and probably others as well), for each element, the CSS engine searches through style rules to find a match. The engine evaluates each rule from right to left, starting from the rightmost selector (called the "key") and moving through each selector until it finds a match or discards the rule. (The "selector" is the document element to which the rule should apply.)

http://code.google.com/speed/page-speed/docs/rendering.html

joggink