I want to only enqueue a script based on a Dropdown selection of a control available for that widget.
Here's what I have tried so far:
1.
public function get_script_depends() {
$scripts = [];
if ( $this->get_settings_for_display( 'layout_style' ) == 'carousel' ) {
$scripts[] = 'jquery-slick';
}
return $scripts;
}
public function after_render() {
$settings = $this->get_settings_for_display();
if ( $settings[ 'layout_style' ] == 'carousel' ) {
$this->add_script_depends( 'jquery-slick' );
}
}
Results:
Both of them don't work.
control-stack.php:1018 saying that the data settings is NULL. So I guess that it's too early to be accessing $settings in the get_script_depends() function.Element_Base class source code and theoretically, after_render() executes after the render() function (as the name suggests) and before the enqueue_scripts() function so this implementation should work (since render() is able to fetch $settings so after_render() should also be able to), but it isn't working.Any help or pointers would be much appreciated.
Solved. In the edit mode, get_script_depends() does not have access to get_settings() or get_settings_for_display() functions, though it has access on the frontend because they execute after the render() trio functions (before, render, after).
So, the solution would be, enqueue all the scripts for edit and preview mode, whereas use conditional enqueue for the frontend.
Example:
public function get_script_depends() {
if (\Elementor\Plugin::$instance->editor->is_edit_mode() || \Elementor\Plugin::$instance->preview->is_preview_mode()) {
return ['jquery-slick', 'other_conditional_script'];
}
if ( $this->get_settings_for_display( 'layout_style' ) == 'carousel' ) {
return [ 'jquery-slick' ];
} else if ( $this->get_settings_for_display( 'condition' ) === 'yes' ) {
return [ 'other_conditional_script' ];
}
}
Most helpful comment
Solved. In the edit mode,
get_script_depends()does not have access toget_settings()orget_settings_for_display()functions, though it has access on the frontend because they execute after therender()trio functions (before, render, after).So, the solution would be, enqueue all the scripts for edit and preview mode, whereas use conditional enqueue for the frontend.
Example: