I’ve come across a fairly obscure problem having to do with measuring a document’s height before the styling has been applied by the browser. More information here:
- http://sonspring.com/journal/jquery-iframe-sizing
- http://ajaxian.com/archives/safari-3-onload-firing-and-bad-timing
In Dave Hyatt’s comment from June 27, he advises simply checking the document.body.offsetLeft property to force Safari to do a reflow.
Can I simply use the following statement:
document.body.offsetLeft;
or do I need to assign it to a variable, e.g.:
var force_layout = document.body.offsetLeft;
in order for browsers to calculate that value?
I think this comes down to a more fundamental question – that is, without being part of an assignment statement, will JavaScript still evaluate a property’s value? Does this depend on whether a particular browser’s JavaScript engine optimizes the code?
The statement will still be evaluated.
Property Accessors | | v v document.body.offsetLeft; ^ |- Identifier ReferenceIn the above statement, you can see that
documentis a Identifier Reference, which is a Primary Expression.Then the property accessor operator is used (
.) too lookup thebodyproperty and then theoffsetLeftproperty.You are not doing an
AssignmentExpressionbut the statement will be evaluated because the Identifier Reference is resolved, and the properties are looked up.Also, host objects, can implement accessor properties that can have a logic
getandsetmethods, not just simple value properties.In ECMAScript 3, we didn’t had the power of creating accessor properties, only the host objects could implement them, but the 5th Edition of the standard allows us to do it.
For example to illustrate:
Note: The above illustrative example works on IE9 Pre, Firefox 3.7alpha, Chrome 5, and WebKit nightly builds.
Then a simple expression as your example, makes the getter to invoke: