I did not actually test this, but one possible solution would be to insert your script in the footer.
If using a widget
When creating a widget, you can add code to the widget() function of your widget class (the function actually displays the widget on the screen). You can call wp_enqueue_script() here, just make sure you mark its use in the footer .
This will print your script where wp_footer() is called, not where wp_head() is wp_head() , but only if the widget is called on the page.
If a line appears in the sidebar
Basically, just filter the sidebar for your row. If the line is present, enter the script in the footer in the same way as with widgets.
(Refresh) Alternatives
There are two more things you can do. First, you can use jQuery to namespace your functionality. Basically, give your widget a unique identifier (say, "my-unique-id"), and then load the script asynchronously:
jQuery(document).ready(function() { if( jQuery('#my-unique-id').length > 0 ) { jQuery.getScript( [your-script-url] ); } }
This code checks if your widget id is on the page ... if so, it loads your script from the server, if not, it does nothing. You can also create this code in PHP to include either a relative or an absolute link to your script file. It depends on you.
Alternatively, you can simply include your script in the built-in <script> block of your widget code. This will work the way you want it, but it violates all kinds of standard encoding methods. The code should usually be located in <header> or placed immediately before the closing </body> ... but you can put it anywhere.
source share