← All posts

Lazy Load YouTube Videos in WordPress with a Free Shortcode

A standard YouTube embed in WordPress loads a pile of YouTube scripts as soon as the page opens, even if the visitor never presses play. This video shows a free shortcode that lazy loads YouTube videos in WordPress: the page shows a thumbnail, and YouTube's scripts load only after someone clicks it. Visitors who never watch the video never download the player.

The baseline: a regular YouTube embed

To see the cost of an embed, we start with an almost empty page and watch the Network tab in Chrome DevTools, filtered to JS.

  1. On the blank page, the only script is jquery.min.js?ver=3.6.0 (89.8 kB).
  2. Paste a YouTube link into the page the regular way and reload.
  3. The JS list now includes www-embed-player.js, base.js (522 kB), fetch-polyfill.js, remote.js, embed.js, cast_sender.js and more. The status bar shows 10 script requests and 751 kB transferred, and the video hasn't been played.

Every visitor pays that cost on every page view, whether they watch the video or not.

Using the lazy load shortcode

The shortcode renders the video thumbnail and waits for a click before it loads YouTube. You only need the video ID, not the full URL.

  1. Add a Shortcode block in the editor.
  2. Copy the YouTube link and keep only the ID, which is the part after watch?v=.
  3. Add the shortcode with that ID and click Update.

This is the shortcode used in the video:

[yt id=oPkaHxvxoso]

The shortcode name comes from the snippet you install, so check which name your copy registers. The current version of the snippet is described as [dp_yt id="..."].

Scripts load only on click

After reloading the page, the video shows up as a thumbnail, and the only script in the Network tab is still jQuery. The page loads a thumbnail image in place of the player.

When you press play, the YouTube scripts load at that moment (their initiator shows autoplay=1), and the video starts. If a visitor never clicks the thumbnail, those scripts are never loaded. On pages with one or more videos, that removes the heaviest YouTube requests from the first page load.

Get the code from our code snippets library: YouTube shortcode with lazy load video and scripts on click