You've identified the fundamental problem, which is a good thing. Likewise, you have recognized that any form of inline scripting contradicts the working principle of a page cache. Actually, the requirement would be predestined for ESI, but ESI also has significant disadvantages that can be so...