Preventing YouTube embeds loading multiple instances of player JS?

I have noticed on many WordPress sites I work on that when there is more than one YouTube video embedded, multiple instances of the player JS will be called.

Since it’s a full megabyte of data, I am trying to determine if there is a way to have only one instance of the JS loaded. I would have thought the second (or more) instances are redundant.

Here’s what gets loaded twice, for a WP page with two embedded videos.

https://s.ytimg.com/yts/jsbin/player-en_US-vfle0WwUC/base.js (1.0MiB)

I’ve been unable to find any information on this, which is a bit surprising as I thought this would be an issue many people would be wanting to solve.

Any suggestions?

Solutions Collecting From Web of "Preventing YouTube embeds loading multiple instances of player JS?"

In theory youtube embedding is done as iframes, and iframe are virtual additional independent web pages which are rendered at the same window, therefor the content of one iframe can not gave an impact on other iframes.

In practice, such JS will be cached in the browser. The first one may get loaded, but the second one (unless someone in google had a big oooops moment) will be “served” from the browser’s cache.

to directly answer the question – there is not much that can be done on wordpress side to avoid it, and most likely there is nothing that need to be done

Google I/O 2011: YouTube’s iframe Player: The Future of Embedding will tell you all about the past’s future. You might be able to find an alternative on to iFrame on the YouTube Developer section but I’d watch that video first on why they chose an iframe.

Most often than not, static assets like JS files are cached by your browser. Meaning future requests pull from your browser’s cache rather than fetch a fresh copy. There is something called a TTL (Time to Live) written in the header of the file that determines how long the item can be cached. Some resources are set to 0, in which case the next request won’t pull from the cache. But my hunch is Google set their TTLs to something pretty reasonable.

If you to find an alternate that allows you to only enqueue a single script and no iframe, consider overriding the default embed for YouTube. Just take note of the first time you create an embed to add the scripts, then every other time after that just show the video markup.

add_filter('embed_oembed_html', 'override_youtube_embed_oembed_html', 99, 4);

function override_youtube_embed_oembed_html($html, $url, $attr, $post_id) {

    static $count = 0;

    $pos = strrpos($url, "youtube.com");
    if ($pos === false) {
        return $html;
    }

    $message = '';
    if( ! $count ) {
        $message = 'First bit of embed magic! ';
    }

    $count ++;
    return $message . "Your Magic Here! How many magics so far? " . $count;
}