Enqueue_scripts() in custom widgets

Hi there,

Current situation:
I’ve made custom widget that provides a Lottie integration. All is working well and its almost ready. At this point I add the lottie-player.js and the lottie-interactivity.min.js (both CDN) in the render code of the widget, this way its not added when the widget is not in use on the page.

Problems:
By doing it this way I have 2 problems.

  1. This is not the best place to add the scripts. It would be better to register them to the head when needed.
  2. If I have 2 lotties in my page, the scripts get added 2 times.

Question:
On the documentation I noticed 2 things: The var $scripts at the top and the function ‘public function enqueue_scripts()’. The thing is. In all the examples they just add scripts by a name. I can’t figure out how to add scripts the right way. Especially scripts that have to be added once, even if the same widget is used multiple times.

Any ideas?
Thanks!

Hi @PandaGerrie

Not sure if you solved your problem yet but to include scripts in your custom element you can do :

public $scripts = [];

public function enqueue_scripts()
{
	wp_enqueue_script('script_name', 'script_url.js', ...);
}

To load it only once, this should work :

public function enqueue_scripts()
{
   if (wp_script_is('script_name', 'enqueued')) {
           return;
   }

	wp_enqueue_script('script_name', 'script_url.js', ...);
}

Hope this helps.

1 Like