Optimize Video Embeds with a Custom Statamic Tag and Alpine.js

lokman musliu

Lokman Musliu

January 23, 2024 · 4 min read · 368 views

Statamic Blogpost Image

Embedding videos directly into your website offers a mix of benefits and challenges. Videos can significantly enhance your content, making it more engaging and informative for your visitors. However, this comes with a potential downside: it may slow down your website's performance. Slow loading times can detract from the overall user experience, which is something we want to avoid.

To address this effectively, we've developed a way that utilizes Alpine.js in combination with a custom Statamic Tag. This powerful combination operates seamlessly in the background to fetch the thumbnail image of the YouTube video you wish to embed on your site.

Using Thumbnail Images for Improved Performance

Starting with the thumbnail image serves a crucial purpose: it allows us to bypass the performance hit that comes with loading a full video player right away. Visitors will initially see a fast-loading image, and if they're interested in watching the video, they can simply click on the thumbnail. At that point, the actual video player will load, ensuring that your site uses resources smartly and doesn't waste bandwidth on videos that may not be watched.

While we've tailored this solution for YouTube, it's designed to be adaptable. With some tweaks, it can be extended to support other video streaming platforms, offering you the flexibility to embed content from various sources without compromising your site's performance.

By following this step-by-step method, you can keep your website speedy and user-friendly while still offering the rich, dynamic content that your audience values.

Step 1: Create a Custom Statamic Tag

We start by generating a custom tag within your Statamic project. Fire up your terminal, navigate to your project's directory, and execute this command:

please make:tag YoutubePreview

Dive deeper into custom tags for Statamic with their official documentation here: Statamic Custom Tags.

Step 2: Writing the Tag

Start by capturing the URL parameter. If it's missing, return a default placeholder image. Then, use Statamic's CoreModifiers class to verify if the URL can be embedded. Failing that, you'll return an empty response.

Here's the code snippet:

$url = $this->params->get('url');

if (empty($url)) {

    return '/assets/placeholder.png';

}

if (!app(CoreModifiers::class)->isEmbeddable($url)) {

    return [];

}

Next, determine if the URL is from YouTube and extract the video ID to craft the URL for the preview image.

if (Str::contains($url, 'youtube.com')) {

    parse_str(parse_url($url)['query'], $newUrl);

    $url = $newUrl['v'];

    $url = "https://img.youtube.com/vi/{$url}/hqdefault.jpg";

} elseif (Str::contains($url, 'youtu.be')) {

    $newUrl = explode('/', $url);

    $url = $newUrl[3];

    $url = "https://img.youtube.com/vi/{$url}/hqdefault.jpg";

}

return $url;

Fully assembled, your custom tag code should look like this:

<?php

namespace App\Tags;

use Statamic\Modifiers\CoreModifiers;
use Statamic\Support\Str;
use Statamic\Tags\Tags;

class YoutubePreview extends Tags
{
    public function index(): array|string
    {
        $url = $this->params->get('url');

        if (empty($url)) {
            return '/assets/placeholder.png';
        }

        if (!app(CoreModifiers::class)->isEmbeddable($url)) {
            return [];
        }

        if (Str::contains($url, 'youtube.com')) {
            parse_str(parse_url($url)['query'], $newUrl);

            $url = $newUrl['v'];

            $url = "https://img.youtube.com/vi/{$url}/hqdefault.jpg";

        } elseif (Str::contains($url, 'youtu.be')) {

            $newUrl = explode('/', $url);

            $url = $newUrl[3];

            $url = "https://img.youtube.com/vi/{$url}/hqdefault.jpg";
        }

        return $url;
    }
}

Step 3: Refreshing Your Frontend Template

In your Antlers template file, create a variable $meta_img to hold the YouTube preview image URLs, populated using the YouTube Preview Tag. This variable is essential for showcasing the video thumbnails.

{{ $meta_img = {youtube_preview :url="video_link"} }}

Feed the video_link from your page's blueprint into the youtube_preview tag you've just crafted.

Step 4: Adding Interactivity with Alpine.js

Alpine.js is the secret sauce for dynamic behavior. It switches between the thumbnail and the embedded video when the user interacts with it. Statamic's directives, like {{ if video_link | is_embeddable }}, confirm that the video can be embedded before it's displayed.

Your final template will resemble this:

{{ $meta_img = {youtube_preview :url="video_link"} }}

<div x-data="{ open: false }" class="mb-8 relative w-full h-full cursor-pointer overflow-hidden aspect-video">
    <div x-show="!open" @click="open = true" x-cloak>
      <img class="object-cover w-full h-auto lazy" src="{{ glide :src="$meta_img" preset='lg' }}" alt="youtube-preview">
    </div>

    <template x-if="open">
        {{ if video_link | is_embeddable }} 
            <iframe src="{{ video_link | embed_url }}?autoplay=1" allow="autoplay" allowfullscreen class="absolute inset-0 w-full h-full"></iframe>
        {{ /if }}
    </template>

    <div x-bind:class="open && 'hidden'" @click="open = true" x-cloak>
        <div class="absolute top-1/2 left-1/2 z-20 transform -translate-x-1/2 -translate-y-1/2 cursor-pointer">
            <div class="play-button"></div>
        </div>
    </div>
</div>

x-cloak is an Alpine.js directive that prevents elements from flickering before Alpine.js initializes. To learn more about directives visit Alpine.js Directives.

To make x-cloak effective, include this CSS in your site.css:

[x-cloak] { 
  display: none !important; 
}

Conclusion

By following these steps, you've seamlessly incorporated a custom YouTube Preview Tag into your Statamic project, enriching the multimedia experience of your site. The synergy of Statamic, Alpine.js, and your new tag creates an interactive and immersive video preview component. Go ahead, experiment, and elevate your web application's capabilities. Enjoy the journey!


Bring Your Ideas to Life 🚀

Kickstart Your Statamic Project with the #1 Statamic Agency

Are you planning a new Statamic project or thinking about migrating your WordPress site to Statamic? Learn more about our expertise as a renowned Statamic development agency.

lokman musliu
Lokman Musliu

Founder and CEO of Lucky Media

Technologies:

Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!