Forum
How would I add a script to bottom of document using a shortcode?
The site I'm working on includes data visualizations in the content. Each visualization is written with javascript using D3.js. I want to use a shortcode to insert the visualization chart in the content and have the JS block that corresponds to that chart to be included at the bottom of the document after D3 is loaded.
My idea is to give a chart ID to each shortcode as a parameter but I'm having trouble figuring out how I could include my script block at the bottom of the document.
It's a very weird situation, even if I could use the shortcodes on a page to add their chart ID to a global array that I could have access to outside of the shortcode itself would be great, I'm just not sure how to approach that.
Creating a shortcode provider is fairly straightforward. Stub out a basic app and then register your provider within it.
I have the shortcode set up and working, I'm just looking for a way for the shortcode to include a script at the bottom of the document. I'm not sure if that's possible though. Even if I could just set a variable inside the shortcode that i would have access to outside of it then I could see that the shortcode is in use on this page and include the script myself.
The script is specific to each data visualization chart so I don't want to load all that javascript for 30 different charts when each chart only appears once on one page of the site.
Thanks for the help, if you can't think of any solutions I'll make something work.
You could have
get_shortcode_replacement()
return a<script>
block that pushes some settings to a location you can access further down the page. That's what we do with the maps field type.