@Font-face and wrong value of the offsetWidth attr

2019-06-16 15:43发布

问题:

I encounter this problem in the latest version of Chromium. After the creation of the first element using a font-family embedded via @font-face I am being handed wrong offsetXyz values. By the time the script is executed, the window.onload hook will already have fired and the font will thus have already been loaded.

This is what the script looks like (schematically):

var e = document.createElement("span");
e["innerText" in e?"innerText":"textContent"] = "fooBar";
e.style.fontFamily = "fontFaceEmbeddedFontFamily";
document.body.appendChild(e);

alert(e.offsetWidth);   // Returns two different values
setTimeout(function() {
  alert(e.offsetWidth); // The latter being correct
}, 1000);

The value is updated "silently". There appears to be no way of waiting for it to correct the values but simply setInterval-check the value and then render the solution. I don't fancy doing dirty stuff like that.

Anyone has any suggestions how to proceed? Happens only when the src: local(" ... ") isn't specified, the issue is hence downloaded-font specific.

回答1:

You have already given the answer yourself. Set src: local() and it will not happen - in general when you use @font-face, stick to the bulletproof syntax, since it was made to overcome browser issues like the one you are butting heads with here.



回答2:

I know is almost a year, but I got this problem too and took me half a day to discover the cause. You can just wait for the entire page to load, instead of using a timeout. The src: local() didn't make any difference for me. So you can use:

<body onload="finished()">

or in jQuery:

$(window).load(
    function() {
        // this only will execute when the entire page is loaded.
    }
);