To avoid a flicker, add
<meta name="color-scheme" content="light dark" />
to the <head> tag, and also put the JavaScript code in <head> so it runs before any content is shown.