On Sun, 16 Apr 2023 at 16:30, Paul Moore <[email protected]> wrote: > > This is probably more of a Javascript question than a Nikola one, but I want > to create a template shortcode that relies on a Javascript library. The dirt > simple approach is to just have a `<script src=xxx>` element in the shortcode > output, but that means that if I use the shortcode twice, I'll be loading the > library twice. And any initialisation I do will happen twice, etc. > > Is there a good way to put some sort of "do this once per page" block into a > shortcode template, so that the actual shortcode logic can rely on it? The > alternative, I guess, is to write a shortcode plugin which adds stuff to > `site.template_hooks["extra_head"]`, but that seems like overkill here... > > Paul
You can’t easily do something like that in shortcodes, as they cannot modify the context used to render pages that contain the post. You could solve this with JS in two ways: 1. The shortcode embeds the full library JS, which checks if a global variable was defined. If it’s defined, it exits without doing anything; if it’s not defined, it defines it and then proceeds to do its thing. This may or may not be good, depending on what the JS library does (if it changes the HTML/DOM when included and not when the document is ready, it will not work if the shortcode appears twice). 2. The shortcode adds a single line of JS that sets a global variable, and then another piece of JS in BODY_END checks the variable and runs the library only if needed. This may be wasteful if you use the shortcode very rarely in your content. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 -- You received this message because you are subscribed to the Google Groups "nikola-discuss" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/nikola-discuss/CAMw%2Bj7JsTCet0MkhYaZNKpbtf-Od73K1cN4Cpp%2BRapk-OtBzJw%40mail.gmail.com.
