9

Im trying to load the twitter widget api in my ajax loaded page.

I have tryed to load the script in a couple of different ways and Im getting the alert to run each time but not the script itself.

So the first time I load the page, then the script is working, but if I go back to the menu and back to this page, then it doesnt load it?

This is the ajax loaded page.

<div id="twitterwid">

<a class="twitter-timeline" width="320" height="500" href="https://twitter.com/my account" data-widget-id="my widget id number">Loading tweets by @me</a>
<script>

alert("alert is working");

!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");


</script>

<div>

Any input appreciated, thanks.

Claes Gustavsson
  • 5,509
  • 11
  • 50
  • 86

2 Answers2

18

All you have to do is: invoke a re-render of the widget tags on the page by calling:

twttr.widgets.load()

Similar question on Twitter Dev Channel

Note: inline script is not executed upon AJAX Load. See: this SO Q&A for the solution to that.

Community
  • 1
  • 1
Ujjwal Singh
  • 4,908
  • 4
  • 37
  • 54
  • Thanks Ujjwal, maybe you can help with another thing? The widget scrolls really bad in the web app and I have tried to set webkit-overflow-scrolling on the surrounding div and on the iframe, but it doesnt help. Do you know how to improve the scrolling? – Claes Gustavsson Jan 28 '13 at 11:16
  • 2
    why i get this ? `Uncaught ReferenceError: twttr is not defined` – prime Feb 15 '15 at 11:14
  • @prime try this: `twttr.ready(function (twttr) { twttr.widgets.load();});` – NineCattoRules Feb 11 '16 at 11:27
0

Add first :

<script>window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));</script>

So you can use :

twttr.widgets.load()
Beber
  • 1,513
  • 15
  • 25