I'm using register_block_type
(see /) to register a Gutenberg block that depends on some Javascript on the frontend.
However, I'd rather the Javascript not be enqueued on absolutely every frontend pageload because the block is usually not used and I don't want to unnecessarily make everyone download the file.
What's the best way to do that?
I'm using register_block_type
(see https://developer.wordpress/block-editor/tutorials/block-tutorial/writing-your-first-block-type/) to register a Gutenberg block that depends on some Javascript on the frontend.
However, I'd rather the Javascript not be enqueued on absolutely every frontend pageload because the block is usually not used and I don't want to unnecessarily make everyone download the file.
What's the best way to do that?
- 1 Does this answer your question? Load CSS/Javascript in frontend conditionally if block is used – Will Commented Feb 17, 2020 at 20:18
1 Answer
Reset to default 2To register scripts/styles conditionally if the page has a certain block you can follow the solution that @Will posted in the comments from a similar question. Copy/pasting with some modifications from that question:
add_action( 'enqueue_block_assets', 'myplugin_enqueue_if_block_is_present' ); // Can only be loaded in the footer
// add_action( 'wp_enqueue_scripts', 'myplugin_enqueue_if_block_is_present' ); // Can be loaded in the both in head and footer
function myplugin_enqueue_if_block_is_present(){
if ( has_block( 'my-plugin/my-block' ) ) {
wp_enqueue_script(
'myplugin_script',
PATH_TO_ASSETS_FOLDER . 'frontend-script.js',
array(),
'1.0.0',
true
);
}
}
If you need information from the block in order to enqueue a certain style or script one way to do this is to enqueue the scripts/styles in the render function of the block.
Beware that although this works we are mixing the enqueue function with the render callback. Another downside of this is that when the callback runs we are already in the content of the post. This means that we can only enqueue in the footer and not in the head.
add_action( 'init', 'myplugin_register_block' );
function myplugin_register_block() {
register_block_type(
'my-plugin/my-block',
array(
'editor_script' => PATH_TO_ASSETS_FOLDER . 'editor-script.js',
'render_callback' => 'myplugin_render_callback'
)
);
}
function myplugin_render_callback( $attributes, $content ) {
// Do not enqueue if we are in the editor.
// This will depend on your use case.
if ( is_admin() ) {
return $content;
}
wp_enqueue_style(
'myplugin_style',
PATH_TO_ASSETS_FOLDER . $attributes['some_attribute'] . '-style.css',
array(),
'1.0.0'
);
return $content;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744740162a4590979.html
评论列表(0条)