/**
* ====================================================
* Performance Optimizations (Additions)
* ====================================================
*/
// Defer non-jQuery scripts
function astra_defer_scripts($tag, $handle, $src) {
if (strpos($handle, 'jquery') !== false) {
return $tag;
}
return '<script src="' . esc_url($src) . '" defer></script>';
}
add_filter('script_loader_tag', 'astra_defer_scripts', 10, 3);
// Defer specific CSS files using media=print trick
function astra_defer_stylesheets($tag, $handle) {
$defer_handles = array('wp-block-library', 'astra-theme-css', 'bookly-css', 'bootstrap-icons');
if (in_array($handle, $defer_handles)) {
return str_replace("rel='stylesheet'", "rel='stylesheet' media='print' onload=\"this.media='all'\"", $tag);
}
return $tag;
}
add_filter('style_loader_tag', 'astra_defer_stylesheets', 10, 2);
// Remove unused styles and scripts
function astra_remove_unused_assets() {
wp_dequeue_style('wp-block-library');
wp_dequeue_script('bookly-js');
wp_dequeue_style('bookly-css');
wp_dequeue_style('bootstrap-icons');
// Remove WordPress emojis
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
}
add_action('wp_enqueue_scripts', 'astra_remove_unused_assets', 100);
// Minify HTML output
function astra_minify_html_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // Remove whitespaces after tags, except space
'/[^\S ]+\</s', // Remove whitespaces before tags, except space
'/(\s)+/s' // Shorten multiple whitespace sequences
);
$replace = array('>', '<', '\\1');
return preg_replace($search, $replace, $buffer);
}
function astra_start_html_minify() {
if ( ! is_admin() && ! is_feed() && ! is_preview() ) {
ob_start('astra_minify_html_output');
}
}
add_action('get_header', 'astra_start_html_minify');
// OPTIONAL: Preload fonts (customize file paths as needed)
/*
function astra_preload_fonts() {
echo '<link rel="preload" href="' . get_template_directory_uri() . '/fonts/your-font.woff2" as="font" type="font/woff2" crossorigin="anonymous">' . "\n";
}
add_action('wp_head', 'astra_preload_fonts', 1);
*/