loading preloaded fonts at the optimal moment

My webfonts are loaded using Webfontloader as shown below:

<script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
<script>
    WebFont.load({
        custom: {
            families: ['BlenderProBook', 'BlenderProMedium']
        }
    });
</script>

Initially, everything works perfectly when the page is first loaded. However, the issue arises when refreshing the page, as it only retrieves the cached fonts after they are requested in HTML and not before my ReactJS app starts running (when the Webfontloader usually fetches them). This timing doesn't work for me because I need to use these fonts in pre-generated SVG.

Is there a way to ensure that the uncached fonts are fetched every time? Alternatively, is there a method to load the cached fonts at the appropriate moment?

Answer №1

I have managed to find a solution for this issue, and I am considering it as my answer unless someone else comes up with a better one.

The font in question is extensively used in the application to calculate text widths and layout requirements. This is why it must be loaded before the app starts running. To prevent the app from running until the font is properly loaded, I decided to implement a test using the text width code.

Here is the code snippet:

var testFont = require('./components/svgText.js');
var timer = setInterval(function () {
    var test = (testFont('TEST', 'BlenderProBook', 20).width === 39.75);
    if (test) {
        clearInterval(timer);
        Router.run(routes, function (Handler) {
            React.render(<Handler/>, document.body);
        });
    }
}, 50);

The `svgTest.js` file utilizes Raphael SVG to generate SVG text and extract measurements in the following manner:

renderedTextSize = function (string, font, fontSize) {
    var paper = Raphael(0, 0, 0, 0);
    paper.canvas.style.visibility = 'hidden';
    var el = paper.text(0, 0, string);
    el.attr('font-family', font);
    el.attr('font-size', fontSize);
    var bBox = el.getBBox();
    paper.remove();
    return {
        width: bBox.width,
        height: bBox.height
    };
};

module.exports = renderedTextSize;

Although testing against a specific width value may seem like a workaround, this approach is proving to be effective in ensuring the proper loading of fonts before the application runs smoothly.

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

Encountering a "Token Error: Bad Request" when attempting to call the callback URL

Every time I try to invoke the callback URL with google-OAuth2, I encounter the following error: Error Traceback: TokenError: Bad Request at Strategy.OAuth2Strategy.parseErrorResponse (G:\projects\oauth\node_modules\passport-oauth ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

To prevent the default alignment in case the text exceeds the input length, stop the automatic alignment

I have a query regarding an input field with a maximum length of 4 characters. The appearance is such that these 4 characters seem to be delineated by borders which are actually 3 lines displayed above the input field. When I enter the fourth character, a ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Connect data dynamically to the p-table based on columns

I'm facing a challenge in displaying JSON data in a table format, and I'm looking for a way to accomplish this using p-table. When looping through the data, I'm noticing duplicate records in the rows. Can anyone guide me on how to achieve th ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...

Exploring the functionality of the load event in JQuery for images

I am encountering an issue with the code provided below: <!DOCTYPE html> <html> <head> <style> </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </hea ...

"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios: Level 1: Min = 2, Max = 50 Level 2: Min = 5, Max = 1000 I've set up an ng-change event on the input field to check if the entere ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

Verify that a minimum of one checkbox has been ticked according to JavaScript guidelines, with appropriate notifications in case

Need help with displaying a message when no checkbox is checked. Currently implementing JavaScript rules and messages <form method="post" enctype="multipart/form-data name="english_registration_form" id="english_registration_form" > <div cl ...

Is it possible to integrate a standard drop-down menu/style into a MUI Select component?

I am currently working on implementing the default drop-down menu style for my MUI Select Component. Here is the desired menu appearance: https://i.stack.imgur.com/GqfSM.png However, this is what my current Select Component looks like: https://i.stack. ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

"Ensure only one checkbox is selected at a time by unchecking the previous

Hi, I'm facing two issues with the code below. The first problem is that when I select checkbox number 3, it automatically selects number 2 as well. I only want this to happen if I manually check it (similar to checkbox number 2). The second issue i ...

Creating a custom PHP webpage and integrating it with a WordPress theme

I'm looking to develop a unique php and javascript page that is integrated with my existing Wordpress theme. Can anyone provide guidance on how to achieve this? Appreciate the help! ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...

Immense trade adhesive navigation bar menu

Currently, I am in the process of enhancing a big commerce website and aiming to implement a sticky menu on scroll. I attempted to use bootstrap along with CSS to achieve this functionality, however, encountered some issues. Below is the snippet of code I ...

Transform socket.on into a promise

Currently, I am developing a service that involves the function init acting as resolve. Initially, it generates a folder using the connection's id and then proceeds to write some default files inside this newly created folder. The main goal here is to ...

Guidance sought on utilizing a callback to retrieve data from mysql using node.js and ejs

I am trying to retrieve the value of foo from the query provided below: exports.get = function(id, cb) { sql = 'SELECT `sidebar`, `test` FROM users WHERE `id` = "' + id + '"'; con.query(sql, function(err, foo) { if (err) ...

Utilize jQuery to select the parent checkbox and mark it as checked

Currently, I am working on a JavaScript function that will automatically check the parent checkbox if a child checkbox is checked. I am implementing this using jQuery and here is my HTML code: <ul id="ulParent" style="margin: 0; padding: 0; list- ...