1

When my page loads I execute JS to determine whether certain text fits inside its parent div. If it doesn't then stuff needs to be done.

The text uses a custom font, which is either loaded via @font-face or Google font, depending on the font.

The problem is that the JS sometimes runs before the font has been applied, leading to a wrong result since the fonts don't have exactly the same size/width.

EDIT, in response to comments:

I have the CSS in the header and the JS at the end of the document. I have now put all my code inside:

$(document).ready ( function(){...})

and the issue is still there.

When I have caching off then it measures the wrong height. When caching is on then it gets the right height, presumably because of the time to apply the font.

user984003
  • 28,050
  • 64
  • 189
  • 285
  • Can you post your code? before seeing your code, have you tried adding your javascript to the bottom of your file so that it loads last? – Full Stack Alien Nov 07 '15 at 00:49
  • Run your code in the `window.onload` function. That should delay it until everything is loaded. – Barmar Nov 07 '15 at 00:50
  • Yes, I add the JS to the bottom and the CSS to the head. – user984003 Nov 07 '15 at 00:50
  • @barmar, I tried putting all the JS inside a "$(document).ready ( function().., but the issue is still there. – user984003 Nov 07 '15 at 01:24
  • `document.ready` runs when the DOM is loaded, but doesn't wait for asynchronous elements to be loaded. – Barmar Nov 07 '15 at 02:34
  • Does this answer your question? [Wait for fonts to load before rendering web page](https://stackoverflow.com/questions/4712242/wait-for-fonts-to-load-before-rendering-web-page) – Zach Saucier Mar 28 '20 at 16:33

2 Answers2

1

I ended up writing JS code that compares the width of two elements: one with a websafe font and one with the font and whose backup font is the same websafe font.

The elements start out with the same width and then become different when the Google font is rendered. The code loops and then exits and runs the rest of the code when the font has been rendered.

The issue with window.onload, for this webpage, is that it also waits for all the images to load, which I do not want my js to wait for.

user984003
  • 28,050
  • 64
  • 189
  • 285
0

try

$(window).load(function(){
    //your code here...
});
Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164