Hey,
I’ve been developing some custom widgets and I’ve run into an issue. I would like to conditionally load front end scripts. I know I can load scripts using:
function initialize(){
$this->register_frontend_scripts( … )
}
However I would like to know if it is possible to conditionally load the scripts depending on what is found in the widget instance. Can I pass in the $instance to the function and read it as I would in the template ($instance[‘field’][‘subfield’]) or is there a specific hook I can use?
Alternatively is it possible to run a $this_>register_frontend_scripts(…) in the template file and include them that way. It saves me checking in the template whether they are already loaded and the loading asynchronously as I would prefer to be using wp_head()
Thanks
Additional: I’m resubmitting this thread as the last one is still waiting on approval and ahs been for 5 days. I would still like to have answer please.
Hi Orin
We actually have a hook designed specifically for this
https://github.com/siteorigin/so-widgets-bundle/blob/develop/base/siteorigin-widget.class.php#L1012
The action would be something along the lines of siteorigin_widgets_enqueue_frontend_scripts_my_widget_id and has 2 arguments. The first is the instance and the second is the widget object.
In any function you hook to this action, you’d call wp_enqueue_script and wp_enqueu_style.
Hopefully that’s enough to point you in the right direction.
Yea I literally just saw this.
I had looked and was trying to use modify_instance to do it but when loading styles they would appear just before the closing tag so not ideal at all.
I’ll give this one a try. I just don’t really like the way it seems to be handling loading Google fonts using dynamically generated LESS/CSS files and then using an import directive as this would create 2 HTTP requests and would allow the script to be loaded more than once ( I would’ve thought, not tested ). So, I’m hoping I can load Google fonts in this way using the wp_enqueue_style and only have them load once.
Thanks for the reply.
Orin