Search code examples
facebook-graph-apiwebinitializationfacebook-javascript-sdkfacebook-apps

Facebook Javascript API Takes A Long Time to Initialize when There Are A Lot of Images on The Page


I recently ran into an issue where Facebook API takes a very long time to initialize when there are a lot of images on the page. I would this is more visible when there are about 50MB of images. Facebook init is actually called first before everything, but it still seems to wait until all images are loaded first. 95% of images are actually appended to the page asynchronously.

Has anyone run into a similar issue? At this point, I'm not sure if it's a bug or how browsers behave, but it's pretty consistent across Chrome and Safari. I have also made sure that there is no synchronous code anywhere that could have blocked the initialization.

Since we rely on Facebook to figure out if user has already logged in by first checking the cookie (or make a call to Facebook if no cookie), this is affecting user's experience quite a bit. We are also using Facebook login as primary way so user is not able to login until the API is initialized.

This is very easily reproducible with slower internet connection. If you want to see the actual behavior, you can go to https://www.toovia.com. Click on login on top right and you will see that Face Pile isn't there i.e. the API is still being initialized.

Here's how I'm initializing the API. It's pretty much copied from Facebook documentation.

var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);

Solution

  • Just FYI. We ended up solving the issue with 3 steps.

    1. We implemented image resizing scheme so the pages now load about 10x faster.
    2. Append the fb element as close to the top as possible.
    3. Implemented a wrapper for Facebook class to handle all dependent classes of FB class so that they can be initialized without having to wait for FB. They are then invoked when FB object is ready to execute whatever logic that is left.

    Our code is rather complex so by having the fb element at the top only without extra steps simply causes too many unexpected issues due to timing. It's also has a lot of performance impact if everything has to wait for FB object to be initialized even though only subset of the logic depends on FB.