I considered a similar approach but thought in javascript it might be flimsy because of an experience I had trying to set a variable within an ajax call. Let me explain:
Javascript evaluated the variable in question before ajax had a chance to change the same variables value, even though I had the ajax written at the top of the script.
So I didn’t know whether javascript was as sequential as say php which I have a little more experience with… Because it was executing code written after other areas of code that hadn’t finished yet…