Complete the code to defer loading of a JavaScript file in WordPress.
function defer_scripts($tag, $handle) {
if ($handle === '[1]') {
return str_replace(' src', ' defer src', $tag);
}
return $tag;
}
add_filter('script_loader_tag', 'defer_scripts', 10, 2);The handle 'main-js' is used to target the main JavaScript file to defer its loading, improving the critical rendering path.
Complete the code to enqueue a stylesheet with media attribute for better rendering performance.
wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom.css', array(), null, '[1]');
Using 'screen' as the media attribute ensures the stylesheet is applied only for screen devices, optimizing rendering.
Fix the error in the code to asynchronously load a script in WordPress.
function async_scripts($tag, $handle) {
if ($handle === 'analytics') {
return str_replace(' src', '[1] src', $tag);
}
return $tag;
}
add_filter('script_loader_tag', 'async_scripts', 10, 2);The attribute must be added as async="async" inside the script tag for valid HTML and proper async loading.
Fill both blanks to conditionally load a script only on single post pages.
function conditional_script_load() {
if ([1]()) {
wp_enqueue_script('single-post-js', get_template_directory_uri() . '/js/single-post.js', array(), null, true);
}
}
add_action('[2]', 'conditional_script_load');Use is_single() to check if the page is a single post, and hook into wp_enqueue_scripts to enqueue scripts properly.
Fill all three blanks to create a critical CSS inline style and defer the main stylesheet.
function inline_critical_css() {
if (is_front_page()) {
wp_add_inline_style('[1]', file_get_contents(get_template_directory() . '/css/critical.css'));
wp_dequeue_style('[2]');
wp_enqueue_style('[3]', get_template_directory_uri() . '/css/main.css', array(), null, 'all');
}
}
add_action('wp_enqueue_scripts', 'inline_critical_css', 20);Use the same handle 'main-style' to add inline critical CSS, dequeue, and then re-enqueue the main stylesheet to defer loading.