I want to measure the size of a text in JavaScript. So far this isn’t so difficult because I can simply put a temporary invisible div into the DOM tree and check the offsetWidth and offsetHeight. The problem is, I want to do this BEFORE the DOM is ready. Here is a stub:
<html>
<head>
<script type="text/javascript">
var text = "Hello world";
var fontFamily = "Arial";
var fontSize = 12;
var size = measureText(text, fontSize, fontFamily);
function measureText(text, fontSize, fontFamily)
{
// TODO Implement me!
}
</script>
</head>
<body>
</body>
</html>
Again: I KNOW how to do it asynchronously when DOM (or body) signals that it is ready. But I want to do it synchronously right in the header as shown in the stub above. Any ideas how I can accomplish this? My current opinion is that this is impossible but maybe someone has a crazy idea.
You don’t have to wait until the entire DOM is ready, just the bits of it you need.
Move the script to just inside
<body>. Nowdocument.bodyexists, so you candocument.body.insertBefore(myspan, document.body.firstChild). (But don’tappendChild, or you’ll be putting an element on top of where the parser is, which will typically break IE.)There may be more complicated workarounds (maybe using a canvas and
measureText()for there?) but this is going to be by far the easiest.