Injecting JavaScript from shortcode?

Apologies if this has already been asked.

I was wondering whether there is a way of injecting js files from within a shortcode? I have a gallery shortcode on my site that requires some additonal js for a lightbox. The js is quite heavy, so I’d rather only load it on pages that actually have a gallery.

If possible, I’d like to be able to check whether a shortcode has been used on a page in the template, and only add the script element if the shortcode has been used at least one. The shortcode is used within markdown, rather than the template. If this worked, I could then extend the system for other components such as accordions or tabs etc.

Does anyone know of any way of achieving something like this?

Currently I have a lightweight js ‘loader’ file that uses a query selector and conditionally requires es6 modules if it finds an element with a certain class, but if possible I’d like to do away with this and just add the script element to the end of the body on pages where it is needed.

1 Like

That should already work if you mark the output in the template as | safe?

Hi keats, thank you. Where would I put the script tag, and how would I check for duplication to ensure it was only loaded once?

You have nth variable for each shortcode. You should include your JS only when this variable is equal to 1.

2 Likes

I’d not seen that nth variable, thank you. I was hoping to find a way of conditionally injecting the files from the page template, so they are all at the end of the body element, but will look into using nth to inject it from the shortcode itself.

Thanks again.

IMO it would be really good to add this use-case to that page on the docs.