Plugin Loading Scripts and Styles on Every Page – Even when not being used

As Rarst already noted, you answered your question. You are telling the software to load those scripts all the time. You need to control that process. Software is stupid. It can’t decide when a good time is to load the code. SO…

Since the plugin should only run when one of its shortcodes are
called, …

Since you say the script should load only when a shortcode is used, go ahead and register your scripts but enqueue then in the shortcode handler, like this from another question:

function my_shortcode( $atts, $content = null ) {
    extract(shortcode_atts(array(
            'title'  => '',
           ), $atts));
    static $counter = 0;
    echo $counter++;
    wp_enqueue_script('wp-mediaelement'); 

}
add_shortcode('enq','my_shortcode');

Your script will load in the footer of the page, so make sure the Javascript can manage that.

As for your stylesheet,

  1. You can load those in the footer of the page similarly to the
    scripts. This is invalid markup but tends to work.
  2. You can load the styles inline in the shortcode, which is a decent
    option, maybe the best one.
  3. You can have the javascript insert the styles dynamically
  4. You can “pre-process” the shortcode, similarly to this (which is a
    resource intensive solution):
    https://wordpress.stackexchange.com/a/101515/21376

Leave a Comment