JS function for Darkmode / Lightmode with value checking via Local Storage gives me a quick color change when going on subpages

I would like to add a button for switching to darkmode and lightmode on my website.

I use var()’s in my css to control the color of my elements.
This is my code:

function loadMode() {
    const mode = localStorage.getItem('mode');
    if (mode === 'dark') {
        setDarkMode();
    }
}

// set darkmode
function setDarkMode() {
    document.documentElement.style.setProperty('--textColor', '#eaeaea');
    document.documentElement.style.setProperty('--backgroundColor', '#333333');
    document.getElementById('toggleMode').textContent = 'Wechsel zu Lightmode';
    localStorage.setItem('mode', 'dark');
}

// set lightmode
function setLightMode() {
    document.documentElement.style.setProperty('--textColor', '#313131');
    document.documentElement.style.setProperty('--backgroundColor', '#e0e0e0');
    document.getElementById('toggleMode').textContent = 'Wechsel zu Darkmode';
    localStorage.setItem('mode', 'light');
}

// toggle the color mode
function toggleMode() {
    const isDarkMode = localStorage.getItem('mode') === 'dark';
    if (isDarkMode) {
        setLightMode();
    } else {
        setDarkMode();
    }
}

// event listener for button
document.getElementById('toggleMode').addEventListener('click', toggleMode);

// load mode on site load
loadMode();

This script is loaded on the end of the webpage (this is the problem, I know, but how can I fix it?)
Now I have the problem that every time I go to a subpage the website is being loaded with the Light Colors and then switched to the dark colors which results in a quick, but very annoying color flicker effect.

How can I prevent this form happening? My website is build with php so sessions could work? Or cookies?

Thank you for helping!

I tried to put the function in the header but then the body element cant receive the color change because I think its not loaded yes(?)