Trigger event upon jQuery being loaded

I’m merging the use of the YouTube iFrame API and jQuery loaded in through a script tag that has the defer flag set. The defer flag must be set as the client has a perfect Google page insight score and wishes to maintain that score.

The YouTube API, upon being fully loaded and ready for use, immediatley calls a function that I define onYouTubeIframeAPIReady. It will then later call onPlayerReady upon the player being fully loaded and rendered.

I wish to use jQuery in this function, but just using jQuery inside the onPlayerReady function will be creating a race condition (hoping the jQuery library has finished loading by the time onPlayerReady gets called).

It occured to me a workable solution would be to use the onPlayerReady function to set a variable before calling a function that tests for both the player and jQuery. Another function sets a variable upon jQuery being ready and calls the same test function.

I have some code that works, but the part that checks for jQuery seems messy to me, and also introduces a small amount of extra unneccessary delay. I was wondering if anyone knows of a better way to run something the instant jQuery becomes available. Basically, are there callbacks for jQuery becoming available built into the library itself?

My current code is as follows:

var ready = {
    'jquery': false,
    'youtube' false
},
testJQueryLoaded;

testJQueryLoaded = function() {
    if(typeof jQuery == 'undefined') {
        window.setTimeout(function() {
            testJQueryLoaded();
        }, 25);
        return;
    }

    ready.jquery = true;
    postLibraryLoad();
};

testJQueryLoaded();

function onYouTubeIframeAPIReady() {
    // Stuff
};

function onPlayerReady() {
    ready.youtube = true;
    postLibraryLoad();
};

function postLibraryLoad() {
    if(!ready.jquery || !ready.youtube) {
        return;
    }

    // More stuff
};

19 thoughts on “Trigger event upon jQuery being loaded”

  1. 107496 805230Hi, Neat post. Theres a issue with your web site in internet explorer, would test this IE still could be the market leader and a big portion of individuals will miss your fantastic writing because of this issue. 82754

    Reply
  2. 666310 39374Aw, this was a really nice post. In concept I wish to put in writing like this moreover ?taking time and actual effort to make an exceptional write-up?even so what can I say?I procrastinate alot and by no means appear to get something done. 489875

    Reply

Leave a Comment