Search code examples
angularimgur

Imgur embed does not show image in Angular web app


Embedded Imgur image does not appear. Sometimes, it appears briefly, then disappears.

This page does not contain the image. It only shows a blank.

Looking at the source, it follows the same Imgur code. It also has embed.js at the bottom of the page.

<blockquote class="imgur-embed-pub" lang="en" data-id="a/lKOEEdd" data-context="false"><br>
    <a href="https://imgur.com/a/lKOEEdd">View on Imgur</a>
</blockquote>

It displays properly when I paste the same HTML on another site, like CodePen.

https://codepen.io/jonasarcangel/pen/OJVOZey


Solution

  • TL;DR;

    Because of server side rendering, your blockquote embed element is processed too early by imgur's scripts. The iframe with its content is then replaced by a blockquote element again when your component is rendered.

    You need to call window.imgurEmbed.createIframe() once your component is rendered client side

    What happens is

    • the server side rendered page is returned by your server, with all html elements, including the blockquote element and a script link to embed.js
    • html data is parsed by the browser
    • embed.js run, and adds a new imgur's script, embed-controler.js
    • that embed-controller.js adds an iframe for all elements matching the selector blockquote.imgur-embed-pub
    • the iframe is displayed and you see the image and replaces the blockquote
    • the client angular app is bootstrapped and performs all the rendering again (Note that this is normal angular universal behaviour)
    • Your app-shell-embed component is rendered, and replaces its content with the blockquote element.

    Solution

    Call window.imgurEmbed.createIframe() in your code once the components with imgur embeds have been rendered to force imgur to do the replacement again;

    if(isPlatformBrowser(this.platformId))//Call the update client side only
    {
        window.imgurEmbed.createIframe();
    }
    

    You can verify this by executing window.imgurEmbed.createIframe() in chrome's dev tools console for the url you posted.