bludginozzie
bludginozzie

Reputation: 119

jQuery mobile with Twitter API

I am upgrading a jquery mobile app to work with the twitter api v1.1. The app has embedded timelines in various different pages that no longer work due to the twitter changes.

I have used the twitter create widget feature which produces code similar to this;

<a class="twitter-timeline" href="https://twitter.com/twitterapi" data-widget-id="YOUR-WIDGET-ID-HERE">Tweets by @twitterapi</a>
<script>!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>

I have embedded this code on my page and everything works great the first time a page is displayed. However on subsequent pages or returns to the same page the embedded timeline does not appear unless I refresh the browser forcing a reload of the page.

I suspect the problem has to do with the way jqm uses ajax for page loading. The twitter javascript must be hooking to the document ready event but this is never called after the first page load since all subsequent pages are loaded via ajax.

I have tried inserting the twitter supplied javascript in to the pageinit event with no success. For example

$(document).on("pageinit", function( event ) {
   // Inserted twitter js here      
});

Any ideas on how to get twitter embedded timelines to reliably appear within a jquery mobile app (without using server code)?

Upvotes: 0

Views: 765

Answers (2)

bludginozzie
bludginozzie

Reputation: 119

I ended up figuring this out. The twitter for websites api adds a window.twttr object and this object has a load method which will scan the dom and install the widgets. This means we can easily check if the widget.js is loaded and if so call it and if not load it. Final code looks something like this;

$(document).bind('pageinit', function() {
    if (window.twttr) {
        twttr.widgets.load();
    } else {
        // Insert twitter supplied widget js here
    }
});

Upvotes: 1

jthompson
jthompson

Reputation: 229

I have a twitter embed working by binding to the 'pagecreate' event. Like so:

// #twitter is my page that I have the embed in
$( '#twitter' ).live( 'pagecreate',function(event){
    //twitter js here
});

Upvotes: 0

Related Questions