4

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.

kayahr
  • 20,913
  • 29
  • 99
  • 147
  • Possible duplicat? http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – jigfox May 18 '10 at 11:24

2 Answers2

4

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>. Now document.body exists, so you can document.body.insertBefore(myspan, document.body.firstChild). (But don't appendChild, 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.

bobince
  • 528,062
  • 107
  • 651
  • 834
1

I'm sorry, but there is no crazy idea. When the DOM is not ready it is impossible to append a node to it, so it is impossible to do what you want at the moment you want.

The sooner event that exists and tell you that the dom is ready is the DOMContentLoaded event, it has other names in different browsers implementations.

Fabien Ménager
  • 140,109
  • 3
  • 41
  • 60