I'm a server-side dev learning the ropes of pure JS these days. This question is about understanding client-side caching via pure JS.
Imagine a web page listing various tweets from users.Each tweet has a "respond to this" button. Pressing it renders a text box.
And if this text box is already rendered, pressing the "respond to this" button merely toggles it off. The JS function responsible for creating this effect is called toggle_reply
.
Upon each page load, I assign the toggle functionality to each "respond to this" button like so:
Array.from(document.querySelectorAll('button.reply')).forEach(btn => btn.onclick = toggle_reply)
This is called at every page refresh. And the page refreshes every time a new tweet comes in - adding the new tweet to the list, and removing old tweets if the list is bigger than 40.
My question is about improving this approach. It feels overkill to me that I'm running this for loop every time there's a fresh. Would there be a way to cache it for buttons that exist on the page and have already been processed by the for loop? An illustrative example of how to do this would be great.