Load CSS elements stylesheets at the head

Hi there,

Im trying to enqueue elements stylesheets based on bricks function to enqueue elements assets:

public function enqueue_scripts() {
wp_enqueue_style( ‘exampleaux’, plugin_dir_url( FILE ) . ‘/examplescss/exampleaux.css’, array(), ‘1.0.1’, ‘all’, false);
wp_enqueue_script( ‘exampleaux’, plugin_dir_url( FILE ) . ‘/examplesjs/exampleaux.js’, array(‘bricks-scripts’), ‘1.0.1’, true);
}

The stylesheets are always loading at the end of the body and I need them at the head. It seems this function always enqueue styles and scripts at the end of the body no matter what.
I dont want to enqueue assets outside of the elements logic as I only want its styles and scripts to be loaded only if the element was called to be in the page.

Looking for a way to enqueue the elements stylesheets at the head only if the element exists on the page. Also would be a nice approach to be able to enqueue asyncrhonous scripts at the head.

Thanks in advance.

1 Like

Hello @themega, have you found a solution for this problem?

You may try to get inspired by Bricks Child Theme

/**
 * Register/enqueue custom scripts and styles
 */
add_action( 'wp_enqueue_scripts', function() {
	// Enqueue your files on the canvas & frontend, not the builder panel. Otherwise custom CSS might affect builder)
	if ( ! bricks_is_builder_main() ) {
		wp_enqueue_style( 'bricks-child', get_stylesheet_uri(), ['bricks-frontend'], filemtime( get_stylesheet_directory() . '/style.css' ) );
	}
} );

While wp_enqueue_style doesn’t offer built-in conditional loading based on element presence, here are two approaches to achieve your goal:

1. Hooks and Conditionals:

  • Use has_block function inside wp_enqueue_scripts to check if the specific block exists on the page.
  • If the block exists, enqueue the stylesheet with $in_footer set to false to place it in the head.

2. Custom Enqueue Function:

  • Create a custom function that takes a boolean condition and the stylesheet details.
  • If the condition (e.g., element existence) is true, use wp_enqueue_style with $in_footer set to false.

Both methods allow conditional loading based on element presence and place stylesheets in the head. Scripts, however, cannot be enqueued asynchronously in the head using core functions. Consider using a plugin like “Enqueue Scripts & Styles” for more advanced enqueueing options, including script placement control.

For a full-stack development course, search online or ask local institutions. Information may change; check for the latest offerings.

@themega @Blackeye found this and it works great Bricks - Enqueues scripts and stylesheets at the document head?