A conditional CSS and JavaScript loader for WordPress

0.1.3 2016-08-23 10:09 UTC

This package is auto-updated.

Last update: 2020-07-08 21:19:37 UTC


A conditional CSS and JavaScript loader for WordPress. It can be used to load files only if a certain CSS class or ID is present on a page.

It uses Filament Group's loadCSS and loadJS.

Warning: Execution order of requested scripts is not managed, so you should not use it to load multiple javascript files that depend on one another.

JavaScript files will be loaded when the DOM is ready. Because of this, your scripts should not contain:

  • document.addEventListener( 'DOMContentLoaded', callback );
  • window.onload
  • jQuery(document).ready(...)

Example of loading JavaScript for a plugin only if the plugin CSS class is present:

function my_load_js() {
	echo wee_Conditional_Loader::js( '.my-plugin-css-class', plugins_url( 'my-plugin', 'script.js' ) );
add_action( 'wp_head', 'my_load_js' ); 

Example of loading CSS for a plugin only if the plugin ID is present:

function my_load_css() {
	echo wee_Conditional_Loader::css( '#my-plugin-id', plugins_url( 'my-plugin', 'style.css' ) );
add_action( 'wp_head', 'my_load_css' );

Of course you can also use it in themes:

function my_theme_conditional_css() {
	echo wee_Conditional_Loader::css( '.my-theme-css-class', get_stylesheet_directory_uri() . '/my-conditional-styles.css' );
add_action( 'wp_head', 'my_theme_conditional_css' );

The JavaScript for this plugin is loaded inline by default and as external files if you are running HTTP/2.0. You can explicitly tell WordPress to use external files by setting the following constant in wp-config.php:

define( 'WEE_CL_LOAD_INLINE', false );

This plugin can also be used to load CSS files asynchronously:

// Register stylesheets.
function my_styles() {
	wp_enqueue_style( 'style-handle-1', 'url/to/style.css' );
	wp_enqueue_style( 'style-handle-2', 'url/to/style.css' ); // We want this to load async.
add_action( 'wp_enqueue_scripts', 'my_styles' );

// Declare async stylesheets.
function my_async_styles( $tag, $handle ) {
	switch ( $handle ) {
		case 'style-handle-2':
			preg_match( "/href='([^']+)'/", $tag, $matches );
			if ( isset( $matches[1] ) ) {
				$tag = '<script>loadCSS( "' . esc_attr( $matches[1] ) . '", document.getElementById( "wee-conditional-loader" ) );</script>' .
					   '<noscript>' . trim( $tag ) . "</noscript>\n";

	return $tag;
add_filter( 'style_loader_tag', 'my_async_styles', 10, 2 );


Walter Ebert