Efficient Script Loading for oEmbeds

I’ve been using FitVids.js in a lot of recent themes to ensure video displays nicely in responsive layouts. I wrote about this in detail for a previous post.

The FitVids script is super tiny (1.7k), and I generally concat it will all my other scripts and then minify using Grunt. So, it’s really not a lot of additional page weight to include the script. However, I was just clued into an alternate method when doing a theme review for the Make theme on wordpress.org that could be slightly more efficient.

Generally FitVids will only be required if video is loaded via an oEmbed (YouTube, Vimeo). So, if we hook into the oEmbed and already have the FitVids registered to load in wp_footer, we can just enqueue the script when it is needed.

How it Works

/**
* Enqueue theme scripts
*/
function prefix_scripts() {
// FitVids Script conditionally enqueued from inc/extras.php
wp_register_script(
'prefix-fitvids',
get_template_directory_uri() . '/js/jquery.fitvids.min.js',
array( 'jquery' ),
'1.0.0',
true
);
}
add_action( 'wp_enqueue_scripts', 'prefix_scripts' );
/**
* Enqueues FitVids, since the embed might be a video.
*
* @since 1.0.0.
*
* @param string $html The generated HTML of the embed handler.
* @param string $url The embed URL.
* @param array $attr The attributes of the embed shortcode.
*
* @return string Returned HTML.
*/
function prefix_embed_container( $html, $url, $attr ) {
// Bail if this is the admin
if ( is_admin() ) {
return $html;
}
if ( isset( $attr['width'] ) ) {
wp_enqueue_script( 'prefix-fitvids' );
}
return $html;
}
add_filter( 'embed_handler_html', 'prefix_embed_container', 10, 3 );
add_filter( 'embed_oembed_html' , 'prefix_embed_container', 10, 3 );

I’ve tested it with my most recent theme, and this method works well. If you visit the home page, you can see FitVids is not enqueued. But if you go to the News or the Video Post, you can see that it is.

Worth It?

Loading an extra script requires an additional HTTP request. So, if your theme is being specifically marketed for a video audience- it probably makes sense to just minify and concat. However, if video is just in one or two posts on the site, it might make more sense to use this method.

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

1 Response

Leave a Reply