Scripting: Loading and Initialization

Updated on Fri, 2014-05-02 00:07

Most Twitter for Websites integrations will be well served by the recommended embed code found in the set-up documentation, but you may want to optimise how and when widgets are initialised for more advanced publishing systems. The widgets-js script provides various functions to help you optimize page performance.

Initializing embedded content after a page has loaded

twttr.widgets.load()

If content is dynamically loaded into a page (such as when lazy-loading content, or using a pushState technique to navigate between articles), it's necessary to initialize TFW widgets contained within that content. To do this, use the twttr.widgets.load() function.

Called without argument, widgets-js will search the entire document.body DOM tree for uninitialized widgets. For better performance, pass either an HTMLElement object, or an array of HTMLElement objects to restrict the search only to children of those nodes.

Example initializing widgets within a single element:

  1. PJAX.fetch('/news/1234').then(function (newArticleElement) {
  2.   twttr.widgets.load(newArticleElement);
  3.   document.body.replaceNode(newArticleElement, oldArticleElement);
  4. });

Example initializing widgets within an array of elements:

  1. PJAX.fetch('/summaries?since_id=1234').then(function (arrayOfSummaryElements) {
  2.   twttr.widgets.load(arrayOfSummaryElements);
  3.   arrayOfSummaryElements.forEach(function (el) {
  4.     document.body.appendChild(el);
  5.   }
  6. });