Run module script before page load?

Here is my problem: I want to redirect users away from this page if they are not logged in. Right now I'm using

<script text="javascript" type="module">
import { getLogInState } from './index.js';

redirectIfNotLoggedIn();

function redirectIfNotLoggedIn() {
    if (!getLogInState()) {
        window.location.replace("#landing");
    }
}
</script>

This imports a function from index.js which retrieves the value of 'loggedIn' from my Vue instance (I am using Vue.JS) only problem is that module type scripts are loaded after HTML so the user briefly (Or longer depending on their connection) sees the content of the page flash before they are brought back to the main page.

So I need to redirect the user if they are not logged into the page before the HTML is loaded, while also accessing an external function. Is this possible? My first idea was to just try calling the function in a separate non-module script since it's already imported by the module script but I don't know if that would actually work and if this script is loading before the rest of the page (and therefore the module) it doesn't matter.
Perhaps there is a better way of accessing Vue root, but I haven't been able to find it either way.

Just to note my website is a SPA that works via jquery, hence the #links. This code is contained in a separate HTML file which is shoved into a 'content' div when you visit it. This shouldn't affect any potential answers but figured I might mention it.



Read more here: https://stackoverflow.com/questions/66342986/run-module-script-before-page-load

Content Attribution

This content was originally published by Shark Interactive at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: