How to delay javascript function until jquery & facebook load?

JQuery provides a very convenient way to delay code execution until the DOM is fully loaded:

$(function() { dom_is_loaded(); }); 

The Javascript SDK for Facebook when run asynchronously provides a similar mechanism:

 window.fbAsyncInit = function() { fb_is_loaded(); } 

What is the most elegant way to delay code execution until the DOM and Facebook SDK are fully initialized?

+4
source share
4 answers

Is there a reason why just doing

 window.fbAsyncInit = function() { $(function() { both_loaded(); }); } 

does not work?

+5
source

Why not:

 var jq_ready = false, fb_ready = false; function bothReady(){ ... } $(function() { dom_is_loaded(); jq_ready = true; if(fb_ready){ bothReady(); } }); window.fbAsyncInit = function() { fb_is_loaded(); fb_ready = true; if(jq_ready){ bothReady(); } } 

I think this is cleaner than setting the interval and will handle the event first.

+3
source

Probably set a flag in your fbAsyncInit function and check it in jQuery loading:

 $(handleLoad); function handleLoad() { if (!facebookLoaded) { setTimeout(handleLoad, 10); // Or 100 or whatever } else { // You're good to go bothLoaded(); } } 

I expect that there is already some global one that you can check if Facebook is loaded (I did not use the Facebook API). If not, you can use your own flag (ideally not global):

 (function() { var fbLoaded = false; window.fbAsyncInit = function() { fbLoaded = true; }; jQuery(handleLoad); function handleLoad() { if (!facebookLoaded) { setTimeout(handleLoad, 10); // Or 100 or whatever } else { // You're good to go bothLoaded(); } } })(); 
+1
source

Source: https://habr.com/ru/post/1346374/


All Articles