• Resolved ballinascreen

    (@ballinascreen)


    Folks,

    In the interests of performance and all round good housekeeping, I’d like to minimise the number of scripts/styles that need to be loaded by the browser depending on which widgets I have enabled – so that when at least one instance of a given widget is enabled, its dependent scripts/styles are enqueued as normal with wp_enqueue_script() and wp_enqueue_style() – and when no instances of a given widget are currently enabled, the depdendent scripts/styles are not enqueued and therefore do not appear in the document output.

    I’ve been looking at some form of mechanism using is_active_widget() but I just can’t seem to make it work – i.e.

    if (is_active_widget('My_Widget_Class'))
    {
      wp_enqueue_script(...)
      wp_enqueue_style(...)
    }

    but it doesn’t seem to work. Note, all my widgets extend the WP_Widget class in order to allow them to be used as multi-widgets in 2.8.x (if that makes any difference).

    Is there a recommended approach to this – or maybe I’m in the right ball-park, but just doing it wrong?

Viewing 5 replies - 1 through 5 (of 5 total)
  • I have the same issue…

    SAME PROBLEM TOO!!!

    Ok… did some research and believe I found a solution!

    First, I am creating my own custom plugins/widgets. The problem I was having is that my custom Widget needs to have some JavaScript code executed in HEAD of HTML document. So, I have it doing like:

    add_action('wp_head','custom_widget_init');
    function custom_widget_init(){
        echo '<script>bla bla bla...</script>';
    }

    BUT, that was causing problems on other site I have running under WordPress MU setup. Needed a way to say.. execute widget code ONLY if it is active for selected site/blog. I am also extending WP_Widget class for my custom widget. The following is my solutions (in short-hand):

    if( is_active_widget( false, false, 'custom_leaders_widget' ) ){
    	add_action('wp_head', 'custom_widget_init');
    }
    
    function custom_widget_init(){
        echo '<script>bla bla bla...</script>';
    }
    class Leaders extends WP_Widget {
    
        /** constructor */
        function Leaders() {
    
    		$widget_ops = array('description' => __('This description', 'Leaders'));
            parent::WP_Widget('custom_leaders_widget', $name = 'Leaders', $widget_ops);	
    
        } // End Leaders

    Hope that makes sense and helps others looking for same solution!

    -JFK-

    Thread Starter ballinascreen

    (@ballinascreen)

    You, my friend, are a star! Works for me too!

    Much appreciated.

    Thanks for explaining this… You should make a tutorial – I am sure many would really appreciate it.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Enqueing dependent scripts/styles only when widget is active’ is closed to new replies.