When adding the ability to share content to Facebook in a web app, use this method to ensure the image loads correctly on the first try.

Sharing content to Facebook is a common feature for many web apps. Ideally this should be done through Facebook’s Share Dialog SDK. You simply provide the URL of the page you want to share.

FB.ui({
  method: 'share',
  href: 'https://example.com/post/1',
}, function(response){}) 

And include Open Graph meta tags in the header of the page (URL) that is being shared:

<meta property="og:image" content="https://example.com/post_image.jpg">
<meta property="og:title" content="Post Title">
<meta property="og:description" content="Post description">

But this method can present a problem if the content being shared contains an image. On the first attempt to share content with an image, Facebook gathers information on the image before serving it back to the share dialog. Specifically, Facebook is getting the dimensions of the image so that it can display it properly. Because of this processing time, the first attempted share of the content fails to load the image in the dialog. Subesquent attempts to share the content will load the image correctly. But you don’t want users having to click share twice.

Luckily there is a fix. Facebook allows you to provide the dimensions of the image as Open Graph tags:

<meta property="og:image:width" content="540">
<meta property="og:image:height" content="720">

Facebook no longer has to calculate the dimensions of the image on their server and the image is therefore loaded correctly on the first share attempt.

So if the content is user generated, how do you programmatically get the dimensions of the image on each page? If you’re using Rails, an easy solution is to use the FastImage gem. Then it’s simply a matter of calculating the image size before adding the Open Graph meta tags (using HAML):

- dimensions = FastImage.size(@post.image_url)
- set_meta_tags og: { @post.image_url }
- set_meta_tags og: { "image:width": dimensions[0] }
- set_meta_tags og: { "image:height": dimensions[1] }