1

What are the best practices for loading scripts for shortcodes?

E.g. I have a gallery shortcode that requires on flickity.min.js (52kb). Shortcode is intended only for gallery pages.

Does separate loading and extra HTTP request overweights not having it on other pages? Or should I concatenate it into the main js file?

Is there a rule of thumb for loading shortcode scripts? For example, if script is less than x kb, concatenate, if more – load separately?

5
  • Possible duplicate of Enqueue Scripts / Styles when shortcode is present
    – kero
    Jul 3, 2017 at 11:25
  • @kero The question is not how to include it but rather when to include vs bundling within main js file
    – Runnick
    Jul 3, 2017 at 11:35
  • then your question is "primarily opinion based" as there is no such rule (at least not to my knowledge) and people can only give their opinion, not a neutral answer. Your question becomes "How to handle JS library that is only needed on specific pages". Bundling has been the go-to answer for that, but since HTTP2 I usually advise against it
    – kero
    Jul 3, 2017 at 12:00
  • 50kb is not too much IMO. You can include it in the main script. People are using 10MB/s connections nowadays.
    – Johansson
    Jul 3, 2017 at 13:16
  • 50 kb is huge for just the js code of only one component of a web page and not everybody use 10 MB/s, specially if you think in mobile users, in several geographic regions or in several conditions that can make the connection low (high mobility, weather, etc). @JackJohansson it seems you don't think in performance so much.
    – cybmeta
    Jul 15, 2017 at 9:03

1 Answer 1

0

Why get into too much mess? Why not just look for your shortcode in content and widgets and then decide whether to enqueue a script/style or not.

Use this code to see if your shortcode is being used or not.

function check_shortcode($text) {

  $pattern = get_shortcode_regex();

   if (   preg_match_all( '/'. $pattern .'/s', $text, $matches )
        && array_key_exists( 2, $matches )
        && in_array( 'myshortcode', $matches[2] ) )
    {
        // myshortcode is being used

        // enque my css and js
        /****** Enqueu RFNB  ******/
        wp_enqueue_style('css-mycss');
        wp_enqueue_script('js-myjs');

        // OPTIONAL ALLOW SHORTCODE TO WORK IN TEXT WIDGET
        add_filter( 'widget_text', 'shortcode_unautop');
        add_filter( 'widget_text', 'do_shortcode'); 

    }

  return $text;

}
add_filter('widget_text', 'check_shortcode');

Code Source

Not the answer you're looking for? Browse other questions tagged or ask your own question.