Note that will not work if someone has javascript disabled.
Javascript redirects should be done as a fallback for meta-refresh redirects in a html documents
Additionally that still doesn’t prevent the original content from being rendered and thus viewable until the javascript executes.
In theme.liquid there is a {{ content_for_layout }} that should also have similar logic adjusted for when it’s not the frontpage or other situations mean to be viewable by non-logged in customers.