Tips for making sure custom fonts are loaded before running any JavaScript code

Upon loading my page, I run a JavaScript function to determine if specific text fits within its parent div. If it doesn't fit, then adjustments must be made.

The text is styled with a custom font, which can be loaded either through @font-face or Google fonts, depending on the font chosen.

An issue arises when the JavaScript executes before the font has been fully applied, resulting in incorrect measurements due to variations in font size and width.

UPDATE: In response to feedback:

I have placed the CSS in the header and the JavaScript at the end of the document. Despite enclosing all my code within:

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

the problem persist.

With caching disabled, the height is calculated incorrectly. Enabling caching yields accurate measurements, presumably because of the time required to apply the font.

Answer №1

After some experimentation, I crafted JavaScript code that meticulously compares the width of two elements: one styled with a websafe font, and the other with the same font but also a backup websafe font.

Initially, the elements exhibit identical widths, but as soon as the Google font is applied, they diverge. The code continuously loops until the font finishes rendering, allowing the rest of the code to execute seamlessly.

One drawback I faced with using window.onload on this webpage is that it waits for all images to load as well, causing unnecessary delays in the JavaScript execution process.

Answer №2

attempt

$(document).ready(function(){
    //insert your code within this function...
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Learn how to use JavaScript and jQuery to alphabetically sort the default td values in a table

This table and script are being used to alphabetically sort the data within the td tags: <button type=button>Sort Options</button> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <t ...

Utilizing AngularJS element.find results in modifications to my objects

Encountering an issue with angularJS when trying to locate elements. It appears that the objects are being altered when using element.find('type').attr('id' ,someid); Here are some additional details: The directive is only used in on ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Broken styles when using Material UI with babel and the 'with styles' feature

We've implemented babel and lerna to maintain specific elements of our react web app separately. While the setup has been effective thus far, we're encountering styling issues when generating the static build. The main project is not processed t ...

Once the content of a page is retrieved through an AJAX request, I am able to access and select tag elements, however, I am unable to

After making an AJAX request, I received an HTML page $.ajax({ async: true, method: 'GET', url: linkPage, // cache: true, success: function (data) { console.log(data); } }); The received data is ...

Static CSS box positioned above dynamic scaling box

Let's Think About It <div id="foo"> Lorem ipsum </div> <div id="bar"> sit amet </div> Is there a way to maintain the size of foo as it is while allowing bar to fill the remaining space on the page when the window size cha ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

Is there a way to connect a controller to rootDocument without using a directive?

I'm currently developing a custom plugin for bootstrapping my Angular application manually, using the document as the root. I want to attach a controller to my root without utilizing the ng-controller directive in order to create a global controller e ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Utilizing AngularJS with dual controllers within a single view

I recently started working on an angularJS web app using a purchased template that has all its controllers, routes, and directives in a single file called app.js. This is my first dive into angularJS and front-end development. Hoping to become a Full Stac ...

Exploring the world of mocking and stubbing in protractor

I am interested in testing my angular application using protractor. The app includes an API Module that communicates with the server In these tests, I would like to mock this API Module. I am not looking to perform full integration tests, but rather tests ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

Tips for enabling Angular JS draggable elements on tablet devices with touch functionality

I've been experimenting with an Angular JS draggable directive. The code I'm using closely resembles the one in this Plunker example. While everything runs smoothly on Windows when using a mouse, I've encountered issues with touch-enabled d ...

Eliminating the background color upon clicking

Here is the link structure I have set up: <ul> <li><a href="home.html"><span>home</span></a></li> </ul> However, when I click on the link, a shadow appears. I would like the link to appea ...

Navigating through a PHP table, tracking your progress with a

I have encountered a problem that I need help with. I have been searching the internet for information on how to add a progress bar to my PHP code. Most solutions I found use the style method to display the progress percentage. In the image below, you can ...

Having trouble inserting an image using Vue?

I am having trouble understanding why only the first image loads, while the others do not. 1. <img :src="require('../assets/batatas.jpg')" :alt="item.title" /> 2. <img :src="'../assets/batatas.jpg'" ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...