javascripttwitterknockout.jscustom-componentknockout-components

How to add a twitter follow button inside a knockout js component?


I am using knockout.js components for my website. I want to add a twitter follow button inside one of my components. As you may know, twitter provides a snippet which can do that using a script.

<a href="https://twitter.com/vishnu_narang" class="twitter-follow-button" data-show-count="false">Follow
        @vishnu_narang</a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

This snippet is supposed to add the twitter follow button using a iframe and other things that the widgets script does.

This works fine outside a component. Example:

<html>
  <body>
    // Snippet here will work as expected
  </body>
</html>

But inside a knockout js component, it doesn't work:

Eg:

<html>
  <body>
    <profile></profile>
  </body>
</html>

// Profile template will be
<div>
   //snippet for follow button here.
</div>

Can someone help me find a way to successfully add a follow button inside such a component?

Note: I'm also using require.js and gulp. Facebook like button renders fine.


Solution

  • The twitter widget javascript, once loaded, immediately scans the DOM to look for elements which need to be turned into widgets. Since you're loading the element dynamically in a component it doesn't actually exist in the DOM until after the twitter javascript has already finished.

    To get around this you can force the widget to scan the dom again by calling twttr.widgets.load() from your component's view model function. Reference

    Sample: jsFiddle