Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Twitter library delay the assignment of its object properties?

The Twitter widget library exposes a global variable twttr. I'd like to modularize this library on the fly using webpack with exports-loader. The problem is that, while the twttr variable is immediately exposed, its properties are still undefined when accessing it synchronously.

console.log(twttr.widgets); // undefined 
setTimeout(function() {
  console.log(twttr); // now defined
});

Live Demo

So, var twttr = require('exports?twttr!./path/to/twitter') will return an object that isn't actually ready to be used.

While the Twitter docs suggest that this is only necessary when loading the library asynchronously, I doubt the widget functions can be used unless wrapped in twttr.ready.

At least webpack offers a nicer way of loading the library and accessing twttr. I suspect the odd behavior is due to this script coming from a time when module systems were non-existent and SRP was neglected. Nonetheless, I'm quite curious what the developers have done to cause this behavior, and my attempt to read the beautified, minified source code has proven folly.

like image 605
m59 Avatar asked Nov 09 '22 22:11

m59


1 Answers

Twitter widget library not only provides API for creating widgets dynamically, but also finds and initializes existing widgets on the page — from the Twitter's documentation page:

By default, widgets-js will find mark-up in a page and convert basic, functional mark-up into rich interactive widgets.

To do that, it has to scan the DOM and replace matching nodes with iframe-s, markup for which are requested from Twitter (which is asynchronous task by its nature).

I suppose, authors decided that initialization of existing widgets may take time and went for doing it completely asynchronously. Now, while library is searching for not yet initialized widgets on the page and updates them, allowing developers to dynamically add new widgets may lead to some concurrency issues. For example it's easy to imagine duplication of requests: library initializer could find a widget added by API and try to initialize it while API has already sent a request to Twitter for iframe's code. The simplest answer to 'How we prevent that?' would be to hide API from the client while library works on existing widgets.

like image 121
sainaen Avatar answered Nov 14 '22 22:11

sainaen