Best practices for shortcode files

I would add some form of scratch variable that is set to true the first time a short code is used. Then add in the output of the shortcode the loading of JS or CSS inline, if your scratch variable is not set, like this:

const script = document.createElement('script')
script.src = '/my/script/file.js'
document.head.append(script)

CSS should be able to be added likewise, with link instead of script and a rel-attribute. I would expect some “flash of content” before the additional scripts/styles are loaded, because they are only loaded after the page loaded fully. Also, if you use external libraries like jQuery you need to have an eye on the order that things are loaded and check if they are available at that point. defer and async are your friends.

In the long term, if you for instance use some form of hook system, you could check for the existence/use of a shortcode in a page via .HasShortcode:

I never tested that though… might play around with it some time.

1 Like