Use localStorage to get dark/light mode when loading a page? [closed]

I have a script to change the css file and it works once the site is loaded but when I reload the page it always applies the dark css file no matter what is stored in localStorage.

javascript:

var darkmode = localStorage.getItem('darkmode');
var theme = document.querySelector("#theme-link");

window.onload = function() {
    setTheme();
};

function setTheme() {
    if(darkmode) {
        theme.href = "dark-theme.css";
    } else {
        theme.href = "light-theme.css";
    }
}

function changeTheme() {
    darkmode = !darkmode;
    setTheme();
    localStorage.setItem('darkmode', darkmode);
}

html:

<head>
    <link rel="stylesheet" id="theme-link">
</head>
<body>
    <img src="img/square.png" onclick="changeTheme()">
    <script src="themechanger.js"></script>
</body>