19

Working on a blog that loads posts on an infinite scroller. Each blog post may or may not have Instagram embeds. I'm finding that the first one that shows on the page will get processed (regardless if it's in the initial page markup, or dynamically added), the following ones will not. Here is a simple JS Bin that illustrates the problem:

http://jsbin.com/hilixi/1/edit?html,js,output

The first Instagram embed is in the initial page markup. Another Instagram embed is added after page load, after 4 seconds. The second embed add does not get processed.

Any ideas why? It seems the Instagram embed script will only run once. Any way I can force it to refresh?

Thanks, Matt

m4olivei
  • 546
  • 1
  • 4
  • 12

3 Answers3

88

The embed.js script that comes with Instagram's embed code has a process function you can call.

window.instgrm.Embeds.process()

Just use that whenever your dynamic content loads.

cy23
  • 1,221
  • 1
  • 10
  • 7
  • 6
    Huh, you don't say. Thank you kind sir. You are a scholar and a gentleman. – m4olivei Dec 10 '14 at 19:50
  • 5
    Had to add this before my

    **``**

    – iRector Feb 15 '17 at 18:32
  • 1
    @iRector I think you don't need the assignment part for `async` and `defer`. This will do the job: ``. See this for more details: https://stackoverflow.com/questions/17169123/defering-javascript-what-is-the-correct-html-syntax-defer-or-defer-defer – papillon Aug 08 '18 at 13:35
1

In your app.js create a directive for adding script element:

.directive('externalscript', function() {
   var injectScript = function(element) {
    var instagramScript = angular.element(document.createElement('script'));
    instagramScript.attr('async defer');
    instagramScript.attr('charset', 'utf-8');
    instagramScript.attr('src', 'http://platform.instagram.com/en_US/embeds.js');
    instagramScript.attr('onload', 'window.instgrm.Embeds.process()');
    element.append(instagramScript);
    var twitterScript = angular.element(document.createElement('script'));
    twitterScript.attr('async defer');
    twitterScript.attr('charset', 'utf-8');
    twitterScript.attr('src', 'http://platform.twitter.com/widgets.js');
    element.append(twitterScript);
};

  return {
      link: function(scope, element) {
          injectScript(element);
      }
  };
})

and then in your html view call:

<div externalscript></div>
0

Inserting this into header and footer area worked for me in WordPress blog.

<script async="" defer="defer" src="//platform.instagram.com/en_US/embeds.js"></script>