Frage

I have an initialise function in my app that I want to trigger when two conditions have been met: 1) the window has loaded: $(window).load() and 2) Typekit has loaded.

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

At the moment, this code is waiting until the window has loaded (including all resources e.g. images) before it starts to load the Typekit web fonts, and then, when they have loaded too, it will initialise.

However, I want Typekit to load before the window has loaded. They should load asynchronously. So:

$(window).load(initialise);

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

Now the Web fonts are loading asynchronously, but the problem is, I need the initialise function to trigger only when both 1) the window has loaded: $(window).load() and 2) Typekit has loaded. Sometimes, the window will load before Typekit has loaded, and sometimes it is the other way round.

So my question is: how can I trigger initialise as soon as both of my criteria have been fulfilled?

War es hilfreich?

Lösung 3

I found a solution that uses jQuery's $.holdReady:

$.holdReady(true);

Typekit.load({
    active: function () {
        $.holdReady(false);
    }
});

$window.load(function () {
    $document.ready(initialize);
});

Andere Tipps

Increment and test at each event. Once ready is positive, initialize will fire:

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

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

        function initialize() {
            //do work
        }
    }

load() ist not the correct method to trigger when window has loaded. It's ready().

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

The ready() method will run the callback immediately if the window is already loaded. The load() method binds an event handler to the load DOM event, which at that moment has already fired. Thus the handler never gets called.

You can use a setInterval and check two variables which will be set

var windowLoaded = false, typeKitLoaded = false, myLoadedInterval = null;
$(window).load(function() { windowLoaded = true; if ( myLoadedInterval == null ) beginInterval(); });
try {
    Typekit.load({ active: function() { typeKitLoaded = true; if ( myLoadedInterval == null ) beginInterval(); } });
} catch (e) {}

function beginInterval()
{
    myLoadedInterval = setInterval(function() {
        if ( typeKitLoaded && windowLoaded ) 
        {
            clearInterval(myLoadedInterval);
            initialise();
        } 
    }, 25);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top