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

Arrange the array depending on the existence of properties in the objects

Is there a way to efficiently organize an array like the following in cases where certain fields are missing? For instance, consider the current array: const users = [ { id: 1, firstname: 'Jerry' }, { id: 2, firstname: & ...

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! ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

How can you effectively load shared header and panel HTML onto pages located in separate directories using jQuery Mobile?

I am currently developing a multi-page application utilizing jQuery Mobile and incorporating loadPage() to retrieve various pages. The overall structure is outlined below. landing.html /app-pages/page1.html /app-pages/page2.html /app-pages/page3.html ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

Determining outcomes of forms added in real-time

Need assistance with dynamically creating tickets, calculating prices, and displaying results when additional tickets are added. Currently facing an issue where price data is not being calculated when a new ticket is added. Any help would be greatly apprec ...

Concentrating on div elements using React

Can the focus() method be used to focus on a div element or any other elements? I have added a tabIndex attribute to a div element: <div ref="dropdown" tabIndex="1"></div> When I click on it, I can see that it gets focused. However, I am att ...

What is the best way to design a dynamic menu using HTML, CSS, and jQuery, where each li element gradually disappears?

Consider this menu structure: <ul class="main-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul> My task is to dynamically hide th ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

How can I reduce the delay in Angular 5 to a minimum?

The following code represents a simple request function: getItem() { return this.http .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {}) .subscribe(response => { ... }); } Depending on the duration of the ...

Adjust the size of a div by clicking a button using Javascript

<script type="text/javascript"> var btn = document.getElementById("btn"); var panel = document.getElementById("panel"); var btn2 = document.getElementById("btn2"); function expandPanel() { btn.style.display="none"; panel.style="overflow:hidd ...

Unable to access the following element using jQuery's next() method

Can someone help me understand how the "next" function works in jQuery? I'm trying to reveal a hidden textarea when a span element is clicked. The hidden textarea is supposed to be the immediate next sibling of the span, but it's not working as e ...

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...

Contrasting .queue() with jquery.queue()

Can someone clarify the distinction between .queue() with .dequeue() and $.queue() OR jquery.queue()? If they serve the same purpose, why did jQuery provide them in two separate documentations? Could someone provide examples to illustrate their difference ...

Guide to integrating jssor into an AngularJS application

Struggling to integrate jssor with angularjs, it seems to be failing because jssor is being initialized before angularjs, causing the ng-repeat elements to not resolve correctly. <div id="slider1_container"> <div u="slides"> <!-- Th ...

Conceal the loading spinner in JQuery once the image has finished loading

I am working with a jQuery function that captures the URL of an image link and displays the image. However, my issue lies in managing the loading process. I would like to display a LOADING message and hide it once the image has fully loaded, but I am strug ...