Embed Javascript Widget in Meteor Template

I am building my first Meteor application and am in a problem with nesting Javascript widgets.

So, my application is the basic landing page of one page, and I'm trying to embed a Twitter timeline widget with the following code ...

<a class="twitter-timeline" href="https://twitter.com/abrudtkuhl" data-widget-id="325157935250546688">Tweets by @abrudtkuhl</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> 

The script tag is never executed, and it only displays the tag. I'm not entirely sure if these are Handlebars (the default template engine for Meteor), or Meteor's problem, as I am relatively new to both frameworks.

+4
source share
2 answers

Generally speaking, when you create a Meteor application, you want to leave your Javascript separate from your template. Try the following:

I assume that <a class="twitter-timeline"... is inside a template called "twitter" (for <template name="twitter"> ). Put your javascript inside a file called twitter.js and call it once when the template is displayed.

 Template.twitter.rendered = function () { ! function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = "//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs"); } 
+12
source

Although @emgee's answer is absolutely correct, in some situations this is not enough.

When JavaScript simply inserts a new element, the next time the JS template is displayed, it will not be reinserted (it already exists), and its initialization will not be called a second time.

This is true for most social widgets, and you need to manually force these widgets to re-analyze the page. This is not only a Meteor problem, but for any site that uploads content to AJAX that contains widgets.

For example, for twitter widgets you need to call twttr.widgets.load(rootElement) .

For example, on the pijs.io homepage for reprocessing inline tweets and the “Follow” button, I have:

 Template.home.rendered = function() { setTimeout(function() { twttr.widgets.load(this.firstNode);; FB.XFBML.parse(this.firstNode); }, 0); } 

Link:

+9
source

All Articles