Adicionar em sites wordpress iframe e vídeos do youtube é péssimo para performance.
Esses recursos adicionam muitas requisições de terceiros, principalmente javascript que aumenta o tempo de execução do site.
Com isso é reduzido o problema que os iframes causam no site de péssimo desempenho em third-parties (Reduce the impact of third-party code).
Adicionar lazy load em iframes
Esse é um vídeo do youtube quando pegamos o código embed:
<iframe width="560" height="315" src="https://www.youtube.com/embed/TukNL7VMxJI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>Para melhorar é preciso adicionar loading=”lazy”, veja como fica:
<iframe loading="lazy" width="560" height="315" src="https://www.youtube.com/embed/TukNL7VMxJI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>Com isso o vídeo só vai ser carregado quando ele aparecer na tela do usuário e isso economiza próximo de 511KB e uma redução de 10s no tempo de interação com da página.
Isso funciona com qualquer tipo de embed com iframe, instagram, spotify, google maps, facebook…
Adicionar loading=”lazy” no wordpress automático
Caso tenha um site com vários vídeos e outros iframes já adicionados, para fazer esse trabalho manualmente é muito demorado.
Nesse caso segue o snippets que pode ser adicionado no functions.php ou usando o plugin Code snippets (recomendado).
Veja porque e como utilizar o plugin Code Snippets no wordpress.
// TODO: Remove once https://core.trac.wordpress.org/ticket/50756 lands.
function wp_lazy_load_iframes_polyfill( $content ) {
// If WP core lazy-loads iframes, skip this manual implementation.
if ( function_exists( 'wp_lazy_loading_enabled' ) && wp_lazy_loading_enabled( 'iframe', 'the_content' ) ) {
return $content;
}
return str_replace( '<iframe ', '<iframe loading="lazy" ', $content );
}
add_filter( 'the_content', 'wp_lazy_load_iframes_polyfill' );Youtube lazyload com bloco gutenberg
O criador desse “plugin”, recomenda criar um arquivo na pasta plugins com o nome youtube_facade.php e ativar no painel de plugins do wordpress.
<?php
/**
Plugin Name: Lazy Load YouTube Embed Block
Plugin URI:
Description: Filters the gutenberg core/embed youtube block content to load a facade until the block is clicked
Version: 1.0
Author: Jem Turner
Author URI: https://jemturner.co.uk
**/
add_filter( 'render_block_core/embed', function( $block_content, $block ) {
// not a youtube embed, dump out original block content
if ( stripos( $block['attrs']['url'], 'youtu' ) === false )
return $block_content;
preg_match( "/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $block['attrs']['url'], $matches );
// if no vid id match, dump out original block content
if ( !isset( $matches[1] ) )
return $block_content;
// get reasonable alt attribute from title or fall back to blank
preg_match( '~title[ ]*=[ ]*["\'](.*?)["\']~is', $block['innerHTML'], $title_matches );
$title_attribute = ( $matches[1] ) ?: '';
// facade magic from https://css-tricks.com/lazy-load-embedded-youtube-videos/
$src_doc = 'srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/'. $matches[1] .'?autoplay=1><img decoding=async src=https://img.youtube.com/vi/'. $matches[1] .'/hqdefault.jpg><span>▶</span></a>"';
$block_content = str_replace( '<iframe','<iframe '. $src_doc, $block_content );
// wptexturize is replacing the quotes in the srcdoc with htmlentities and breaking things
// so it's disabled here. this does mean you lose smart quotes etc. in the rest of the content
// for pages that contain a youtube video embed, but is that a massive problem? x
remove_filter( 'the_content', 'wptexturize');
return $block_content;
}, 10, 2 );Vai aparecer um novo bloco gutenberg para adicionar vídeos do youtube automaticamente com a tag loading=”lazy”.
Código javascript e css para melhor carregar youtube em qualquer site
Encontrei um script que chama youtube lite, desenvolvido pelo site labnol.org, esse script não carrega o vídeo, apenas uma imagem do vídeo com outra imagem play em cima, muito parecido com um vídeo.
Ao clicar na imagem o script carrega o vídeo para execução, evitando o carregamento e desperdício de recursos.
O código está no codepen.io: https://codepen.io/labnol/pen/vYXYrOW
Alternativa para todos sites mais simples
Em alternativa encontrei no site dev.to um desenvolvedor que fez um código parecido, mas utilizando srcdoc, a vantagem é que não precisa adicionar nenhum código adicional, todo JS e CSS já vem dentro do iframe:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/Y8Wp3dafaMQ"
srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/Y8Wp3dafaMQ?autoplay=1><img src=https://img.youtube.com/vi/Y8Wp3dafaMQ/hqdefault.jpg alt='Video'><span>▶</span></a>"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
title="video"
></iframe>Basta substituir o https://www.youtube.com/embed/Y8Wp3dafaMQ final do URL do youtube que identifica o vídeo, em 3 diferentes lugares.