I was wondering how to check if a css file is already loaded. For example, I have in my theme Font Awesome font-awesome.min.css and I have a plugin that make use of Font Awesome too. So, I ended up with two font-awesome.min.css stylesheets loaded. Is there a way to check if a CSS sheet is already loaded before I enqueue it.

2 Answers
2

I’ve +1 the Ravs answer because it it good and it should works in most case, however it assumes that you know the handle used by 3rd party theme/plugins and this is not always true.

If all developer used same handle for same styles/scripts the problem does not exists, because WordPress automatically skip styles and scripts registered with same handle.

But let’s assume you register the css using:

wp_enqueue_style('font-awesome', ... );

and another plugin use

wp_enqueue_style('fontawesome', ... );

WordPress will load file 2 times.

In most cases developer tend to use just the name of the css without extension, but this is not a rule and also can be different version, e.g.

wp_enqueue_style('font-awesome.min', ... );

An alternative aproach is lookin at the file names of registered script, looking at global $wp_styles that contain an arrays of all the registered scripts, something like:

add_action('wp_enqueue_scripts', 'check_font_awesome', 99999);

function check_font_awesome() {
  global $wp_styles;
  $srcs = array_map('basename', (array) wp_list_pluck($wp_styles->registered, 'src') );
  if ( in_array('font-awesome.css', $srcs) || in_array('font-awesome.min.css', $srcs)  ) {
    /* echo 'font-awesome.css registered'; */
  } else {
    wp_enqueue_style('font-awesome', get_template_directory_uri() . '/font-awesome.css' );
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *