del header (crítico) | o justo antes de (no crítico). | 3. Agrupar el JS retirado en un \n"; } add_action('wp_head', 'alcastromol_optimizer_print_header_assets', PHP_INT_MAX); function alcastromol_optimizer_print_footer_assets() { if (!alcastromol_optimizer_is_active()) { return; } alcastromol_optimizer_print_style('alcastromol-optimizer-deferred', 'deferred.css'); } add_action('wp_footer', 'alcastromol_optimizer_print_footer_assets', PHP_INT_MAX); function alcastromol_optimizer_filter_link($tag) { $href = alcastromol_optimizer_tag_attr($tag, 'href'); $rule = $href !== '' ? alcastromol_optimizer_rule_for_url($href) : null; $rel = strtolower(alcastromol_optimizer_tag_attr($tag, 'rel')); if ($rule && !empty($rule['remove']) && (strpos($rel, 'stylesheet') !== false || strpos($rel, 'preload') !== false)) { return ''; } if (!$rule || empty($rule['async']) || strpos($rel, 'stylesheet') === false) { return $tag; } $tag = preg_replace('#\smedia=(["\']).*?\1#i', '', $tag); $tag = preg_replace('#\sonload=(["\']).*?\1#i', '', $tag); $tag = preg_replace('#\s*/?>\s*$#', '', $tag); $async = $tag . ' media="print" onload="this.media=\'all\'">'; $fallback = ''; return $async . $fallback; } function alcastromol_optimizer_filter_script($tag) { $src = alcastromol_optimizer_tag_attr($tag, 'src'); if ($src === '') { return $tag; } $rule = alcastromol_optimizer_rule_for_url($src); if (!$rule) { return $tag; } if (!empty($rule['remove'])) { return ''; } if (!empty($rule['nowprocket']) && stripos($tag, 'data-nowprocket') === false) { return preg_replace('#]*>#is', function ($match) { return alcastromol_optimizer_filter_link($match[0]); }, $html); $html = preg_replace_callback('#]*\bsrc=(["\']).*?\1[^>]*>.*?#is', function ($match) { return alcastromol_optimizer_filter_script($match[0]); }, $html); return $html; } function alcastromol_optimizer_start_buffer() { if (!alcastromol_optimizer_is_active()) { return; } ob_start('alcastromol_optimizer_filter_html'); } add_action('template_redirect', 'alcastromol_optimizer_start_buffer', 100); /* |-------------------------------------------------------------------------- | Admin |-------------------------------------------------------------------------- */ add_action('admin_menu', function () { add_submenu_page( 'alcastromol-functions', 'Optimizador de archivos', 'Optimizador', 'manage_options', 'alcastromol-optimizer', 'alcastromol_optimizer_admin_page' ); }, 21); add_action('admin_bar_menu', function ($bar) { if (!current_user_can('manage_options')) { return; } $bar->add_node([ 'id' => 'alcastromol-optimizer', 'parent' => 'alcastromol-tailwind', 'title' => 'Optimizador de archivos', 'href' => admin_url('admin.php?page=alcastromol-optimizer'), ]); }, 91); function alcastromol_optimizer_notice($type, $message) { set_transient('alcastromol_optimizer_notice_' . get_current_user_id(), [ 'type' => $type, 'message' => $message, ], MINUTE_IN_SECONDS); } function alcastromol_optimizer_redirect() { wp_safe_redirect(admin_url('admin.php?page=alcastromol-optimizer')); exit; } add_action('admin_post_alcastromol_optimizer_scan', function () { if (!current_user_can('manage_options')) { wp_die('No tienes permisos.'); } check_admin_referer('alcastromol_optimizer_scan'); $scan = alcastromol_optimizer_scan(); if (is_wp_error($scan)) { alcastromol_optimizer_notice('error', $scan->get_error_message()); } else { alcastromol_optimizer_notice( 'success', sprintf('Detección lista: %d CSS y %d JS en la portada.', count($scan['css']), count($scan['js'])) ); } alcastromol_optimizer_redirect(); }); function alcastromol_optimizer_posted_flag($row, $flag) { return !empty($row[$flag]); } add_action('admin_post_alcastromol_optimizer_save', function () { if (!current_user_can('manage_options')) { wp_die('No tienes permisos.'); } check_admin_referer('alcastromol_optimizer_save'); $scan = alcastromol_optimizer_get_scan(); $known = []; foreach (['css', 'js'] as $type) { foreach ((array) ($scan[$type] ?? []) as $asset) { if (!empty($asset['key'])) { $known[$asset['key']] = $asset; } } } $posted = isset($_POST['assets']) && is_array($_POST['assets']) ? wp_unslash($_POST['assets']) : []; $rules = alcastromol_optimizer_empty_rules(); foreach (['css', 'js'] as $type) { foreach ((array) ($posted[$type] ?? []) as $key => $row) { $key = sanitize_key($key); if (!isset($known[$key]) || !is_array($row)) { continue; } $remove = alcastromol_optimizer_posted_flag($row, 'remove'); $critical = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'critical'); $deferred = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'deferred'); $bundle = $type === 'js' && alcastromol_optimizer_posted_flag($row, 'bundle'); $async = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'async'); $nowprocket = $type === 'js' && alcastromol_optimizer_posted_flag($row, 'nowprocket'); if ($critical || $deferred || $bundle) { $remove = true; } if ($critical) { $deferred = false; $async = false; } if ($deferred) { $async = false; } if ($bundle) { $nowprocket = false; } if ($async || $nowprocket) { $remove = false; $critical = false; $deferred = false; $bundle = false; } if (!$remove && !$async && !$nowprocket) { continue; } $rules[$type][$key] = [ 'key' => $key, 'url' => $known[$key]['url'], 'remove' => $remove, 'critical' => $critical, 'deferred' => $deferred, 'bundle' => $bundle, 'async' => $async, 'nowprocket' => $nowprocket, ]; } } $errors = alcastromol_optimizer_build_bundles($rules); if (is_wp_error($errors)) { alcastromol_optimizer_notice('error', $errors->get_error_message()); alcastromol_optimizer_redirect(); } if ($errors) { foreach ($errors as $url) { foreach (['css', 'js'] as $type) { foreach ($rules[$type] as $key => $rule) { if ($rule['url'] === $url) { $rules[$type][$key]['remove'] = false; $rules[$type][$key]['critical'] = false; $rules[$type][$key]['deferred'] = false; $rules[$type][$key]['bundle'] = false; } } } } } update_option(ALCASTROMOL_OPTIMIZER_RULES_OPTION, $rules, true); if ($errors) { $errors = alcastromol_optimizer_build_bundles($rules); } if (is_wp_error($errors)) { alcastromol_optimizer_notice('error', $errors->get_error_message()); } elseif ($errors) { alcastromol_optimizer_notice('error', 'No se pudo leer algunos archivos, así que no se retiraron: ' . implode(', ', $errors)); } else { alcastromol_optimizer_notice('success', 'Optimización guardada.'); } alcastromol_optimizer_redirect(); }); function alcastromol_optimizer_asset_label($asset) { if (!empty($asset['id'])) { return preg_replace('/-(css|js)$/', '', $asset['id']); } $path = wp_parse_url($asset['url'], PHP_URL_PATH); return $path ? basename($path) : $asset['url']; } /* |-------------------------------------------------------------------------- | Caché en .htaccess |-------------------------------------------------------------------------- */ function alcastromol_optimizer_htaccess_file() { return ABSPATH . '.htaccess'; } function alcastromol_optimizer_htaccess_lines() { return [ '', ' ExpiresActive On', ' ExpiresByType image/webp "access plus 1 year"', ' ExpiresByType image/png "access plus 1 year"', ' ExpiresByType image/svg+xml "access plus 1 year"', ' ExpiresByType image/x-icon "access plus 1 year"', ' ExpiresByType font/woff2 "access plus 1 year"', ' ExpiresByType application/font-woff2 "access plus 1 year"', ' ExpiresByType text/css "access plus 1 year"', ' ExpiresByType application/javascript "access plus 1 year"', ' ExpiresByType text/javascript "access plus 1 year"', '', '', '', ' ', ' Header set Cache-Control "public, max-age=31536000, immutable"', ' ', ' ', ' Header set Cache-Control "public, max-age=0, must-revalidate"', ' ', '', ]; } function alcastromol_optimizer_htaccess_enabled() { $file = alcastromol_optimizer_htaccess_file(); if (!is_readable($file)) { return false; } $contents = file_get_contents($file); return is_string($contents) && str_contains($contents, '# BEGIN Alcastromol Cache'); } function alcastromol_optimizer_write_htaccess($enabled) { $file = alcastromol_optimizer_htaccess_file(); if (!file_exists($file) || !is_writable($file)) { return new WP_Error('alcastromol_htaccess', 'No se puede escribir el archivo .htaccess.'); } $contents = file_get_contents($file); if (!is_string($contents)) { return new WP_Error('alcastromol_htaccess', 'No se pudo leer el archivo .htaccess.'); } $start = '# BEGIN Alcastromol Cache'; $end = '# END Alcastromol Cache'; $lines = preg_split("/\r\n|\n|\r/", $contents); $kept = []; $inside = false; foreach ($lines as $line) { if (!$inside && str_contains($line, $start)) { $inside = true; continue; } if ($inside && str_contains($line, $end)) { $inside = false; continue; } if (!$inside) { $kept[] = $line; } } while ($kept && trim((string) end($kept)) === '') { array_pop($kept); } if ($enabled) { $kept[] = ''; $kept[] = $start; foreach (alcastromol_optimizer_htaccess_lines() as $line) { $kept[] = $line; } $kept[] = $end; } $kept[] = ''; if (file_put_contents($file, implode("\n", $kept)) === false) { return new WP_Error('alcastromol_htaccess', 'No se pudo guardar el archivo .htaccess.'); } return true; } add_action('admin_post_alcastromol_optimizer_htaccess', function () { if (!current_user_can('manage_options')) { wp_die('No tienes permisos.'); } check_admin_referer('alcastromol_optimizer_htaccess'); $enabled = !empty($_POST['htaccess_cache']); $result = alcastromol_optimizer_write_htaccess($enabled); if (is_wp_error($result)) { alcastromol_optimizer_notice('error', $result->get_error_message()); } elseif ($enabled) { alcastromol_optimizer_notice('success', 'La caché de un año quedó escrita en .htaccess.'); } else { alcastromol_optimizer_notice('success', 'Se quitó la caché de .htaccess.'); } alcastromol_optimizer_redirect(); }); function alcastromol_optimizer_admin_page() { if (!current_user_can('manage_options')) { return; } $scan = alcastromol_optimizer_get_scan(); $rules = alcastromol_optimizer_get_rules(); $notice = get_transient('alcastromol_optimizer_notice_' . get_current_user_id()); if ($notice) { delete_transient('alcastromol_optimizer_notice_' . get_current_user_id()); } $active = function_exists('alcastromol_is_module_active') && alcastromol_is_module_active('optimizer'); ?>

Optimizador de archivos

Detecta los CSS y JS de la portada. En cada archivo eliges si se retira su URL, si el CSS retirado entra al grupo crítico del header o al grupo no crítico de antes de </body>, si el JS retirado entra al script global del header, si el script conserva data-nowprocket, o si el CSS se carga con media="print" onload="this.media='all'".

El optimizador está apagado. Actívalo en Centro de funciones para aplicar estos cambios en el sitio.

Caché en .htaccess

Imágenes, iconos, fuentes, CSS y JS se guardan un año. El HTML queda sin caché. El bloque se agrega al final de .htaccess y no modifica las reglas de WordPress ni las de WP Rocket.

Activa en .htaccess
Última detección: · · CSS · JS

Archivo Retirar URLQuita el link o el script CSS crítico<style> en el header CSS no crítico<style> antes de </body> media="print"onload="this.media='all'" JS global<script> en el header data-nowprocketWP Rocket no lo procesa
'Retirar URL', 'critical' => 'CSS crítico en el header', 'deferred' => 'CSS no crítico antes de cerrar body', 'async' => 'media print', 'bundle' => 'JS global en el header', 'nowprocket' => 'data-nowprocket', ]; ?> >