Last active
April 27, 2022 22:22
-
-
Save johndwells/d56ee4b87d3d2384bb1d01824680cb23 to your computer and use it in GitHub Desktop.
Lazyload Youtube/Vimeo player with AlpineJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lazyload Youtube/Vimeo player with AlpineJS
The following snippet will "lazyload" a Youtube/Vimeo player, by:
<button>
tag)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:
asset
is an Asset element, where the file is a JSON file generated by the Embedded Assets plugin@webroot/dist/svg/play.svg
(courtesy of a Vite build)