Measure text size in JavaScript

I want to measure the size of text in JavaScript. So far it’s not so difficult, because I can just put a temporary invisible div in the DOM tree and check offsetWidth and offsetHeight. The problem is that I want to do this before the DOM is ready. Here is the 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 this asynchronously when the DOM (or body) signals that it is ready. But I want to do this synchronously right in the header, as shown in the header above. Any ideas how I can do this? My real opinion is that this is not possible, but maybe someone has a crazy idea.

+4
source share
2 answers

You do not need to wait until the entire DOM is ready, but only its bits.

Move the script only inside the <body> . Now document.body exists, so you can document.body.insertBefore(myspan, document.body.firstChild) . (But not appendChild , or you'll put the element on top of where the parser is located, which usually interrupts IE.)

There may be more complex workarounds (perhaps using canvas and measureText() for there?), But this will be the easiest.

+4
source

Sorry, but no crazy idea. When the DOM is not ready, it is impossible to add a node to it, so it is impossible to do what you want at the moment you want.

The sooner the event exists and tells you that dom is ready, this is the DOMContentLoaded event, it has different names in different browser implementations.

+1
source

Source: https://habr.com/ru/post/1310107/


All Articles