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.

6
  • 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? Commented Nov 7, 2015 at 0:49
  • Run your code in the window.onload function. That should delay it until everything is loaded. Commented Nov 7, 2015 at 0:50
  • Yes, I add the JS to the bottom and the CSS to the head. Commented Nov 7, 2015 at 0:50
  • @barmar, I tried putting all the JS inside a "$(document).ready ( function().., but the issue is still there. Commented Nov 7, 2015 at 1:24
  • document.ready runs when the DOM is loaded, but doesn't wait for asynchronous elements to be loaded. Commented Nov 7, 2015 at 2:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

try

$(window).load(function(){
    //your code here...
});

1 Comment

Sorry, I meant to say does NOT fix the issue. (Deleted that comment)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.