Skip to content

Instantly share code, notes, and snippets.

@johndwells
Last active April 27, 2022 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johndwells/d56ee4b87d3d2384bb1d01824680cb23 to your computer and use it in GitHub Desktop.
Save johndwells/d56ee4b87d3d2384bb1d01824680cb23 to your computer and use it in GitHub Desktop.
Lazyload Youtube/Vimeo player with AlpineJS
{% set video = craft.embeddedAssets.get(asset) %}
{% if video %}
<div x-data="{ play : false }"
class="relative"
style="padding-bottom: {{ video.aspectRatio ~ '%' }}">
<button x-show="!play"
x-on:click.prevent="play = true"
class="group block"
aria-label="Play video">
<img src="{{ video.image }}"
class="absolute inset-0"
alt="{{ video.title }}">
<span class="absolute inset-0 flex transition-opacity text-white opacity-80 group-focus-visible:ring group-focus-visible:opacity-100 group-hover:opacity-100">
{{ svg('@webroot/dist/svg/play.svg')|attr({ class: 'block m-auto w-[60px] h-[60px]' }) }}
</span>
</button>
<template x-if="play">
{{ tag('iframe', {
src: video.getVideoUrl(['playsinline=1', 'autoplay=1']),
class: 'w-full h-full absolute inset-0',
frameborder: 0,
allow: 'accelerometer; autoplay; encrypted-media; fullscreen; gyroscope; picture-in-picture, playsinline',
title: video.title,
}) }}
</template>
</div>
{% endif %}
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@johndwells
Copy link
Author

Lazyload Youtube/Vimeo player with AlpineJS

The following snippet will "lazyload" a Youtube/Vimeo player, by:

  • On page load, display the video's slate image, with a white SVG play icon on top (all wrapped in a <button> tag)
  • When the button is clicked, hide it and in its place render and display the iframe

Previously we were able to accomlish this without Javascript using this clever method:

https://css-tricks.com/lazy-load-embedded-youtube-videos/

However, recent versions of Chrome (and possibly others) do not allow "autoplay" using this technique. As a result, users are forced to click twice to actually play the video. :(

But luckily, the "click" that users take in this below method does signal to the browser that autoplay is allowed.

This snippet is built for Craft CMS; specifically it might be part of a project based on our agency's starter project: https://github.com/onedarnleyroad/craftcms

Assumptions:

  • Tailwind 3.x (or ^2.1 w/JIT enabled)
  • Craft Embedded Assets plugin installed
  • asset is an Asset element, where the file is a JSON file generated by the Embedded Assets plugin
  • The video asset is from Vimeo or Youtube
  • The "play" SVG icon exists at @webroot/dist/svg/play.svg (courtesy of a Vite build)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment