I have an assortment of useful velocity macros that are commonly used multiple times on a page. These macros rely on some shared javascript components. What I think I need to do is:
- detect the first instance of the macro on the page. If first, then load up the shared javascript.
- generate a unique ID for this instance of the script.
The way I have been doing this up until now is straightforward and worked perfectly until recently when it is suddenly… not. Here’s my once-working and now-broken approach.
Step 1: I check a variable at the beginning of the script. If it is zero or null or whatever, this is the first instance and I (a) set it to 1, and (b) load up the shared components. If it is non-zero, I skip the shared loading and increment the variable.
For example:
#if (!$macroID)
#set($macroID = 1)
<load up shared components>
#else
#set($macroID = $macroID + 1)
#endif
<rest of macro>
Step 2: I then use $macroID to generate a unique ID for a blank html element. I’ll then call the shared javascript function and point it to that element so it can do whatever the macro is supposed to do. For example:
#set ($uniqueID = "macroName-" + $macroID)
<script type="text/javascript">
console.log("macroName id=$uniqueID"); // here for debugging
require(['jquery'], function($) {
shared_table_generation_function($, "$uniqueID", $arguments);
});
</script>
<table id="$uniqueID">
</table>
This is all pretty simple and used to work 100% of the time. Now it works… sometimes. Other times the initial if (!$macroID) seems to fail, and I get multiple instances that think they’re the first one. Or else there is some parallelism going on and there is no guarantee of in-order execution of macros. Here’s the console output from one of my pages with a large number of calls to the same macro: the important thing is the number at the end of the line, which is the value of $uniqueID:
The duplicates are the killer, breaking the whole strategy (I no longer have unique IDs in my HTML elements). The fact that there are multiple instances that think they’re the first is also Not Good. Can anyone explain this behavior? Even better, tell me how to avoid it?
I would be thrilled to be told I’m Doing It All Wrong and be shown a better way.
Thanks in advance!
(oh, we’re running 16.10.9 at the moment)
