I have an issue. One of my JS scripts needs Facebook SDK and Twitter widgets JS to load first. Facebook creates FB object, Twitter creates twttr object. Both of them create these objects AFTER my script fires, even though they’re loaded from <head>.
I think solution is to periodically check if FB and twttr are defined, and then proceed with executing my script. But I have no idea how to do this.
I tried creating a loop
while (typeof FB === 'undefined' || typeof twttr === 'undefined' || typeof twttr.widgets === 'undefined') {
// run timeout for 100 ms with noop inside
}
But this clearly does not work as it keeps firing timeouts at a high speed and page hangs.
Please help me, I can’t sleep because of this issue.
If the scripts are loaded in the normal, synchronous way, then just make sure that your
<script>include appears after the library scripts in the document’s<head>. If, on the other hand, those scripts are loading objects asynchronously (as seems to be the case), then create something like this:And use it like this:
The function given in the second argument to
whenAvailablewill not execute untiltwttris defined on the globalwindowobject. You can do the same thing forFB.Important note: Those libraries probably also provide some built-in way to execute code after they have loaded. You should look for such hooks in their respective documentation.