so-widgets-bundle icon indicating copy to clipboard operation
so-widgets-bundle copied to clipboard

Load Widgets More Efficiently

Open gregpriday opened this issue 10 years ago • 2 comments

At the moment, the classes and associated PHP files for each active widget is loaded on every page request. We've heard from a few users that this is causing quite a bit of overhead, especially when there are a lot of custom active widgets.

It would be ideal to use some sort of auto loading.

There are a few challenges to this though. A big one is how to property register widgets with siteorigin_widget_register.

This was suggested on our forums: https://siteorigin.com/thread/performance-widgets-are-loaded-on-every-page/

gregpriday avatar Dec 04 '15 13:12 gregpriday

Hi and thank you for this great plugin !

Can we get an update on this issue ? Have you found out how to make it work ?

arnofo avatar Mar 23 '16 08:03 arnofo

For a custom widget that needed to call an API before building the widget form fields, my class looked like the following:

class My_Optimized_Widget extends SiteOrigin_Widget {

	private $widget_form;

	function __construct() {
		
		parent::__construct(
			// Setup things
		);

	}

	function initialize() {
             

		if ( $this->can_setup_widget_form() ) {

			// Do your expensive stuff

			// Now setup the form fields
			$this->widget_form = array(
				// Setup form array
			);

		}

	}

	function get_widget_form() {
		return $this->widget_form;
	}

	function can_setup_widget_form() {
		global $pagenow;

		// 1. Only proceed if it is a admin-ajax.php request
		if ( 'admin-ajax.php' !== $pagenow ) {
			return;
		}

		// 2. Only proceed if $_POST has a widget key
		if ( ! array_key_exists( 'widget', $_POST ) ) {
			return;
		}

		// 3. Only proceed if widget-key value is the Name of the widget class
		if ( 'My_Optimized_Widget' !== $_POST['widget'] ) {
			return;
		}

		return true;

	}
	
}

So, before setting up the form field array in the initialize() function, I checked for those three conditions.

unfresco avatar Jan 15 '22 13:01 unfresco