Skip to content

Commit

Permalink
fix (performance): add frontend variables only when there is a block …
Browse files Browse the repository at this point in the history
…that needs them (#3019)

* conditionally add args through filters

* refactored implementation

* added comments

* Update src/init.php [skip ci]

* encode args as json

* Removed spaces [skip ci]

---------

Co-authored-by: prconcepcion <[email protected]>
Co-authored-by: Benjamin Intal <[email protected]>
  • Loading branch information
3 people authored Jan 17, 2024
1 parent b242b30 commit 8b86975
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions src/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ function __construct() {

add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );

// Adds a special class to the body tag, to indicate we can now run animations.
add_action( 'wp_footer', array( $this, 'init_animation' ) );
add_action( 'wp_footer', array( $this, 'init_stackable_vars' ) );

// Add the fallback values for the default block width and wide block width.
// These are used for the inside "Content width" option of Columns.
add_action( 'stackable_inline_styles', array( $this, 'add_block_widths' ) );
Expand Down Expand Up @@ -98,12 +102,6 @@ public function register_frontend_assets() {
wp_register_script( 'ugb-block-frontend-js', null, [], STACKABLE_VERSION );
}

$args = apply_filters( 'stackable_localize_frontend_script', array(
'restUrl' => get_rest_url(),
'i18n' => array(), // Translatable labels used in the frontend should go here.
) );
wp_localize_script( 'ugb-block-frontend-js', 'stackable', $args );

// Register inline frontend styles, these are always loaded.
// Register via a dummy style.
wp_register_style( 'ugb-style-css-nodep', false );
Expand Down Expand Up @@ -440,6 +438,30 @@ public function add_body_class_theme_compatibility( $classes ) {
public function load_plugin_textdomain() {
load_plugin_textdomain( 'stackable-ultimate-gutenberg-blocks' );
}

/**
* Adds a special class to the body tag, to indicate we can now run
* hover transitions and other effects.
*
* @see src/styles/block-transitions.scss
*
* @return void
*/
public function init_animation() {
echo '<script>requestAnimationFrame(() => document.body.classList.add( "stk--anim-init" ))</script>';
}

/**
* Adds the stackable object with frontend constants if needed.
*
* @return void
*/
public function init_stackable_vars() {
$args = apply_filters( 'stackable_localize_frontend_script', array() );
if ( ! empty( $args ) ) {
echo '<script>stackable = ' . json_encode( $args ) . '</script>';
}
}
}

new Stackable_init();
Expand Down

0 comments on commit 8b86975

Please sign in to comment.