Written on 14. December 2021 by Lennart Christensen

Check if a stylesheet is already loaded in WordPress

Assuming a plugin loads a style file like this:

wp_enqueue_style('bootstrap_css', ... );

And so if we assume that in your theme you register the same css file like that

wp_enqueue_style('bootstrap-css', ... );

In those cases, WordPress will load two files with perhaps the same styles.

To only get script to load once you need to find identification / handle of the 3rd party theme / plugin script. To find it, you can open the source code of your page, search for stylesheet, and look at its id tag attribute. The script ID is also the identification in WP script registration, however with the addition of -css in the end. So in this example, in the sourche code it will be bootstrap-css-css and because they do not have the same identification then there will be two and the other will be bootstrap_css-css. Remember to remove "-css" when name the Handle. Unfortunately, you can not do the same for js scripts, so you need to search in the code files to find the handle ID.

Now you can rename your script handle to match it from 3rd party, in that way the script loads only once.

Another way to do this is by checking if the script exists before adding the script.
In this case, you also need to know the identification of the script from the 3rd party.

function cco_scripts() {

	// First we get some handles and in an array
	$handles = [ 'css-bootstrap', 'bootstrap-cco', 'bootstrap' ];
	
	// So we run thru al handles if not excists we add bootstrap
	foreach ($handles as $handle) {
		if ( !wp_style_is( $handle, $list = 'enqueued' ) ) {
			wp_enqueue_style( 'css-bootstrap', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css', null, '4.1.0' );
		}
	}
}

In your ad_action the 3rd parameter should be max mean apply this action when all scripts or styles loaded. You can do this both in plugin and theme development.

add_action('wp_enqueue_scripts','cco_scripts',999);