Why does this Twitter library delay assignment of object properties?

Twitter widget library provides twttr global variable. I would like to modulate this library on the fly using webpack with export-loader. The problem is that although the twttr variable twttr immediately displayed, its properties are still undefined when accessed 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 is actually not ready for use.

While Twitter docs say that this is only necessary when loading the library asynchronously, I doubt that widget functions can be used if they are not packaged in twttr.ready .

At the very least, the web package offers a more convenient way to download the library and access twttr . I suspect that the odd behavior is due to this script coming from a time when there were no module systems, and SRP was ignored. However, I am very curious what the developers did in order to trigger this behavior, and my attempt to read the improved, reduced source code proved crazy.

+5
source share
1 answer

The Twitter widget library not only provides an API for creating a widget dynamically, but also finds and initializes existing widgets on the page - from the Twitter page

By default, widgets-js will find the markup on the page and convert the basic functional markup into rich interactive widgets.

To do this, he needs to perform a DOM scan and replace the corresponding nodes with iframe -s, markup for which data is requested from Twitter (this is an asynchronous task by nature).

I believe the authors decided that initializing existing widgets may take some time and for this is completely asynchronous. Now, when the library searches for not yet initialized widgets on the page and updates them, which allows developers to dynamically add new widgets, it can lead to some concurrency problems. For example, it is easy to imagine duplicate requests: the library initializer can find the widget added by the API and try to initialize it, and the API has already sent a request to Twitter for iframe code. The simplest answer to the question: "How do we prevent this?" it would hide the API from the client while the library is working with existing widgets.

+1
source

Source: https://habr.com/ru/post/1207707/


All Articles