Skip to main content

Darek Greenly

Personal blog, expect game dev and web stuff

Twitter widget refresh

The script described may not work anymore.

I couldn’t find anything in the Twitter Embedded Timelines documentation that would let me set refresh interval so I made my own. At first I thought I could simply reset the iframe’s src attribute, which usually would reload frame’s content. But Twitter’s widget didn’t had src attribute.

I found a solution. It’s really quick and dirty one, but it works. You can get and modify it to your needs. I’ve only tested it with list’s timeline.

Twitter’s widget

At the moment of writing, Twitter’s HTML code for timeline widgets looks like this:

<a
	class="twitter-timeline"
	data-dnt="true"
	href="https://twitter.com/THE-LINK"
	data-widget-id="THE-ID"
>
	Tweets from me
</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>

First part is a link which would be replaced by the iframe. Secondly, new file is attached to our <head> - platform.twitter.com/widgets.js. Important thing is, that the code checks if widgets.js was already loaded.

How to reload it?

As mentioned, the rendered iframe doesn’t have src attribute so one way would be to clear previously created scripts and elements and launch the twitters code again. We’ll have to remove both the iframe and widgets.js from our header.

// Twitter refresher "class"
var TwitterRefresh = function (options) {
	this.id = options.id;
	this.code = options.code;
};

TwitterRefresh.prototype.doRefresh = function () {
	document.getElementById(this.id).innerHTML = this.code;
	document.getElementById('twitter-wjs').remove();
	// Run twitter's code to attach widget.js
	/* PASTE THE SECOND PART OF YOUR CODE HERE */
};

// Create new instance
var twtrefresher = new TwitterRefresh({
	id: 'twitterRefresher',
	code: 'PASTE THE FIRST PART OF YOUR CODE HERE',
});

And now, whenever you want to refresh the widget - just run twtrefresher.doRefresh();. You could easily do it with setInterval, but I’ll leave it up to you!

Comments