WordPress – only load widget JS when necessary

I’m new to wordpress development and created a widget that works fine, however I’m not sure how to dependently load the necessary JS for the widget.

Current code is:

Read More
wp_enqueue_script('my_script', '/path/to/necessary.js');

class widget extends WP_Widget {
    function widget(){
        ....
    }
}

I’d like to only load that script if/when the widget is actually included on the page. Since it’s not on every page, I’m wastefully loading JS on some pages. If I put the wp_enqueue_script in the widget function, it doesn’t work since it’s in the template loop and the headers have already been written out. I know I can just drop a <script> tag into the widget function, but that seems to go against WP standards, so I’m looking for the “correct” way to do this.

Related posts

Leave a Reply

2 comments

  1. Most WordPress widgets are used on all “user” – rather than admin – pages. Basically you need to determine what pages load the widget, test for it, and if it passes, add the script to the header. If it is just the front page, then you can test for that with php in the header and enqueue the script… If it is a page with a specific category, check for that and enqueue the script… you get the picture. The wordpress codex is your friend