functions.php
/**
* Esta función agrega los parámetros "async" y "defer" a recursos de Javascript.
* Solo se debe agregar "async" o "defer" en cualquier parte del nombre del
* recurso (atributo "handle" de la función wp_register_script).
*
* @param $tag
* @param $handle
*
* @return mixed
*/
function mg_add_async_defer_attributes( $tag, $handle ) {
// Busco el valor "async"
if( strpos( $handle, "async" ) ):
$tag = str_replace(' src', ' async="async" src', $tag);
endif;
// Busco el valor "defer"
if( strpos( $handle, "defer" ) ):
$tag = str_replace(' src', ' defer="defer" src', $tag);
endif;
return $tag;
}
add_filter('script_loader_tag', 'mg_add_async_defer_attributes', 10, 2);
// Ejemplo con "async".
wp_register_script( 'fichero-js-async', get_stylesheet_directory_uri() . '/js/fichero.js', [], false, true );
wp_enqueue_script( 'fichero-js-async' );
// Ejemplo con "defer".
wp_register_script( 'fichero-js-defer', get_stylesheet_directory_uri() . '/js/fichero.js', [], false, true );
wp_enqueue_script( 'fichero-js-defer' );
Comments