Execute JavaScript function after the window has finished loading, regardless of any asynchronous downloads

In my app, there is an initialise function that I want to execute only when two conditions are met: first, the window has finished loading ($(window).load()), and second, Typekit has loaded.

$(window).load(function() {
    try {
        Typekit.load({ active: initialise });
    } catch (e) {}
});

Currently, this code waits for all resources, such as images, to finish loading before it starts loading the Typekit web fonts. After the fonts have loaded, then the initialisation process begins.

However, I need Typekit to load before the window finishes loading in an asynchronous manner. Therefore, the revised code should be:

$(window).load(initialise);

try {
    Typekit.load({ active: initialise });
} catch (e) {}

Now, the Web fonts load asynchronously. The challenge now is ensuring that the initialise function triggers only when both conditions have been met. Sometimes, the window loads before Typekit, and other times the opposite happens.

So, how can I ensure that initialise is triggered once both criteria are fulfilled?

Answer №1

Test and advance with each occurrence. When the variable ready becomes positive, the function initialize will be triggered:

   {
        var ready = -1;
        $(window).load(function() {
            if (++ready) initialize();
        });

        try {
            Typekit.load({
                active: function() {
                    if (++ready) initialize();
                }
            });
        } catch (e) {}

        function initialize() {
            //perform necessary tasks
        }
    }

Answer №2

load() is not the best choice for triggering actions when the window has finished loading. It's better to use ready().

Typekit.load({
    active: function () {
        $(document).ready(initialize);
    }
});

The ready() method will execute the callback immediately if the window is already loaded. On the other hand, the load() method attaches an event handler to the load event of the DOM, which may have already occurred by that point. Therefore, the handler may never be called.

Answer №3

I came across a clever fix that utilizes jQuery's $.holdReady:

$.holdReady(true);

GoogleFonts.load({
    ready: function () {
        $.holdReady(false);
    }
});

$window.ready(function () {
    $document.ready(initializePage);
});

Answer №4

To ensure that both the window and Typekit are loaded, you can create a setInterval function that checks for two variables being set.

var isWindowLoaded = false, isTypeKitLoaded = false, myInterval = null;
$(window).load(function() { isWindowLoaded = true; if (myInterval == null) startChecking(); });
try {
    Typekit.load({ active: function() { isTypeKitLoaded = true; if (myInterval == null) startChecking(); } });
} catch (error){}

function startChecking()
{
    myInterval = setInterval(function() {
        if (isTypeKitLoaded && isWindowLoaded) 
        {
            clearInterval(myInterval);
            initialize();
        } 
    }, 25);
}

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

Effectively monitoring coordinates on both the client and server sides

I'm currently in the process of developing a multiplayer game using websockets, node, and JavaScript. I need advice on the most effective approach to update client information and manage their coordinates on the server. The method I am using at the mo ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Challenges Arising from CGI Scripts

One requirement for the user is to input text into a designated text field within a form element in my HTML. Following this, a CGI script processes the user's input and JavaScript code is responsible for displaying the processed information. JavaScri ...

Express Vue Production Problem

I've been attempting to implement SSR in my Vue app, and to achieve this I've incorporated the vue-plugin-ssr extension. To run it with express, I created a new file named server.mjs containing the following code: import express from "expres ...

Is your Scrollmagic failing to function once your website is uploaded to the server?

My website incorporates Scrollmagic to dynamically load sections (changing opacity and adding movement) as users scroll through it. Everything functions perfectly fine when I preview the HTML file on my computer, but once I uploaded it to my hosting serv ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { display: inline; position: rel ...

Troubleshooting a problem with jQuery waypoints in a static HTML/JS

Utilizing waypoints and windows to display the panels similar to the fiddle example I have created: http://jsfiddle.net/6bMMa/1/ Everything is functioning correctly, however, I have only managed to make it work by using id numbers on the panel divs. The ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

Ways to fix the error "Response must contain an array at." when creating a dropdown menu

I encountered an error while trying to create a dropdown menu. I referred to the documentation available at The response must include an array at " . ". Although I came across some links with potential solutions, none of them seemed to work for me: https ...

jQuery width property does not seem to be functional on menus that do not contain any dropdown

I am currently working on creating a menu that displays arrows underneath the items when hovered over or when the .active class is added to the menu. Everything is working fine, except for the fact that it only works on menus with drop-downs and the child ...

Guide to generating a downloadable link using React and Express

In my React app, I have a button which is essentially a div. The Button Component returns this structure with all other elements as props: <button className={"button "+styleButton} onClick={handleClick}> {source && <img src= ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

What factors determine how a React component should be re-rendered based on a specific file?

I am facing a challenge with a file that stores an array of objects. There is a component responsible for fetching data from this file and rendering the list. The issue arises when the file gets updated externally, as I need the component to reflect these ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...