Course contentsShow
← Web Development
Lesson 2833 of 2,98250. Third-Party IntegrationsFree lesson

Twitter/X Embed Integration

Embed tweets and timelines using Twitter's widget.js, handling dark mode and responsive sizing.

Twitter/X Embed Integration

What you'll learn: How to embed tweets and timelines using Twitter's widget.js script while handling dark mode and responsive sizing.

The Core Idea

Twitter (now X) provides a JavaScript widget library that transforms simple HTML markup into rich, interactive embedded content. Instead of manually building tweet UI, you include widgets.js from Twitter's CDN, which finds specially-formatted links or <blockquote> elements and replaces them with fully-rendered tweets or timelines.

Basic Tweet Embed

Place this HTML where you want the tweet to appear:

<blockquote class="twitter-tweet">
  <a href="https://twitter.com/user/status/1234567890"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

The script scans your page and transforms matching elements into embedded tweets. Notice the async attribute — you learned this prevents blocking page rendering.

Dark Mode Support

Control theme with a data-theme attribute:

<blockquote class="twitter-tweet" data-theme="dark">
  <a href="https://twitter.com/user/status/1234567890"></a>
</blockquote>

To dynamically switch themes based on user preference, detect their system theme and reload the widget programmatically.

Responsive Sizing

Twitter embeds adapt automatically to their container width. Control width and alignment with data-width and data-align:

<blockquote class="twitter-tweet" data-width="550" data-align="center">
  <a href="https://twitter.com/user/status/1234567890"></a>
</blockquote>

Timelines

Embed entire user timelines similarly:

<a class="twitter-timeline" href="https://twitter.com/username">Tweets by @username</a>

The same widgets.js script processes these anchors and transforms them into scrollable timelines.

Key Takeaway: Twitter's widgets.js transforms simple HTML markup into rich embeds, with theme and sizing controlled through data- attributes for dark mode and responsive layouts.