javascript 动态添加嵌入时,Instagram 嵌入不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27408917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:27:33  来源:igfitidea点击:

Instagram embeds not working when adding embeds dynamically

javascriptjqueryinstagram

提问by m4olivei

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:

处理在无限滚动条上加载帖子的博客。每篇博文可能有也可能没有嵌入 Instagram。我发现页面上显示的第一个将被处理(无论它是在初始页面标记中还是动态添加的),后面的则不会。这是一个说明问题的简单 JS Bin:

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

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.

第一个 Instagram 嵌入在初始页面标记中。页面加载后 4 秒后添加另一个 Instagram 嵌入。第二个嵌入添加没有得到处理。

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

任何想法为什么?看来 Instagram 嵌入脚本只会运行一次。有什么办法可以强制它刷新?

Thanks, Matt

谢谢,马特

回答by narwic

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

Instagram 嵌入代码附带的 embed.js 脚本有一个可以调用的处理函数。

window.instgrm.Embeds.process()

Just use that whenever your dynamic content loads.

只要您的动态内容加载时使用它。

回答by Darko Kostic

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

在你的 app.js 中创建一个用于添加脚本元素的指令:

.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:

然后在您的 html 视图调用中:

<div externalscript></div>

回答by Himanshu Sachdeva

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

在 WordPress 博客中将其插入页眉和页脚区域对我有用。

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