16/04/2022

Remove Unused CSS and JS on WordPress

Remove Unused CSS and JS on Wordpress

Unused CSS and JS files on WordPress can slow down the website. These files may be default files on WordPress or may have come from any plugin. It can speed up the website by deleting these unused files. To remove the style files, add the codes you need below into the functions.php file.

Remove Default WordPress CSS and JS


Remove Emoji Scripts

Wordpress Emoji Script

/* Remove Emoji Scripts */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );

Remove Emoji Styles

Wordpress Emoji Styles

/* Remove Default Emoji CSS */
remove_action( 'wp_print_styles', 'print_emoji_styles' );

Remove WordPress Global Style

Wordpress Global Style

/* Remove Global Style 'id="global-styles-inline-css"' */
remove_action( 'wp_enqueue_scripts', 'wp_enqueue_global_styles' );

Remove WordPress Feeds (application/rss+xml)

Wordpress Feed RSS

/* Remove application/rss+xml */
remove_action( 'wp_head', 'feed_links', 2 ); 
remove_action( 'wp_head', 'feed_links_extra', 3 );

Remove WordPress RSD (application/rsd+xml)

Wordpress RSD

/* Remove application/rsd+xml */
remove_action( 'wp_head', 'rsd_link' );

Remove WordPress Wlwmanifest (application/wlwmanifest+xml)

Wordpress Wlwmanifest

/* Remove application/wlwmanifest+xml */
remove_action( 'wp_head', 'wlwmanifest_link' );

Remove Shortlink

Remove Unused Shortlink

/* Remove rel="shortlink" */
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );

Remove WordPress Generator

Remove WordPress Generator

/* Remove WordPress Generator */
remove_action( 'wp_head', 'wp_generator' );

Remove Other CSS and JS

You can remove the CSS added with the <link rel=”stylesheet”> element with the following code.

wp_dequeue_style();

The following sample code <link rel='stylesheet' id='wp-block-library-css' href='' media='all' /> can be used to remove CSS code. The CSS link to be removed is determined by the ID with wp_dequeue_style, it is not necessary to use the “-css” suffix at the end of the ID.

/* Remove <link rel="stylesheet" CSS> */
add_action( 'wp_enqueue_scripts', 'remove_styles' ); 
function remove_styles() { 
     wp_dequeue_style( 'wp-block-library', get_stylesheet_uri() ); 
}

Remove Style On Specific Page

For remove unused CSS file on specific WordPress page use the code below.

/* Remove Style On Spesific Page */

add_action('wp_print_styles','_remove_style',100);

function _remove_style(){
global $post;
$pageUrl = get_permalink($post->ID);
if( $pageUrl=='https://example.com/page1/' ) {
    wp_dequeue_style('wp-block-library');
  }
}

Reference: https://stackoverflow.com/questions/38633991/how-to-remove-style-css-on-specific-wordpress-page