Measure text size in JavaScript

Posted by kayahr on Stack Overflow See other posts from Stack Overflow or by kayahr
Published on 2010-05-18T11:17:21Z Indexed on 2010/05/18 11:20 UTC
Read the original article Hit count: 173

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html