How to Print all Loaded JS and CSS Stylesheets handle for Your WordPress?

in Tutorials on April 3, 2019

How to get a complete list of CSS style sheets and JS scripts loaded by the theme and extensions under WordPress? Obtaining such a list is of obvious interest when you are looking to optimize the performance of your site.

Indeed, it is not rare that some scripts are loaded on all pages of your site even if you could limit the loading to a page template, a content type or any other element of your WordPress architecture .

Developers use the wp_enqueue_script and wp_enqueue_style functions to load JavaScript and CSS respectively. Most of the time they are not packaged because it is often impossible to know on what content you will need the proposed functionality.

However, when you develop a custom theme and you master the entire development project, it is much easier to set such conditions. For example, you can limit the loading of WooCommerce CSS on pages that display products, the shopping cart and the order page.

To create nothing more simple because WordPress provides globals that are $ wp_scripts and $ wp_styles. We need to create a loop on these variables in order to extract the information.

The function below can be placed the functions.php file of your theme or in a mu-plugins. It is conditioned to display the data only to the administrators of the site.

In this tutorial we will go over steps which displays all loaded Java Scripts and Style Sheets CSS.

function wpadn_list_css_js() {
	if (! is_admin() && is_user_logged_in() && current_user_can('manage_options')) {
		// JavaScript list
		global $wp_scripts;
		foreach($wp_scripts->queue as $handle) :
			echo "Handle: " . $handle . '
';
		endforeach;
	 
		// CSS list
		global $wp_styles;
		foreach($wp_styles->queue as $handle) :
			echo "Handle: " . $handle . '
';
		endforeach;
	}
}
add_action('wp_print_scripts', 'wpadn_list_css_js');

It is possible to retrieve a lot of information about each loaded item. In this case, only the name of the script interests us because it is it that we pass in the functions wp_dequeue_script and wp_dequeue_style which have the effect of disabling the loading of the specified scripts.

The quest for the best loading time is a long way that will make you learn new things in development. Borrow it with curiosity to understand how themes and extensions work in WordPress.

Categories: Tutorials