Can we put this snippet in a separate js file and include it (I should've done it originally, but even more reason to do it now that it has become somewhat more complicated)?