wp-react-boilerplate icon indicating copy to clipboard operation
wp-react-boilerplate copied to clipboard

A suggestion for conditional script loading

Open jamigibbs opened this issue 9 years ago • 2 comments

If we don't conditionally enqueue admin.js, which is rendering based on a specific DOM element (wp-react-component-library in this case), a console error will trigger on all pages other than the one created for the plugin.

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

A solution would be to assign a global variable to add_menu_page and pass that into the enqueue hook to check conditionally:


static function admin_enqueue_scripts($hook) {
  global $menu_page;
  if ( $menu_page != $hook ) {
    return;
  }
  wp_enqueue_script( 'wp-react-boilerplate-admin', plugins_url( 'build/admin.js', __FILE__ ), array(), 'v0.0.1', true );
}

static function add_admin_page() {
  global $menu_page;

  $menu_page = add_menu_page(
    'WP React Component Library',
    'Component Library',
    'manage_options',
    'wp-react-component-library',
    array( 'WP_React_Boilerplate', 'render_component_library' )
    );
}

jamigibbs avatar Oct 23 '16 21:10 jamigibbs

Yeah, this was a bit sloppy on my part. I'll fix it up.

gcorne avatar Oct 29 '16 02:10 gcorne

Hello, if can help you, I have fixed this issue on PR https://github.com/gcorne/wp-react-boilerplate/pull/9

Odyno avatar Jan 30 '17 11:01 Odyno