Having the CSS and JS in the html template produces pages larger than necessary, as each page need to contain all the js/css. Separating them in appropriate files allow the browser to just download them once and use them for all the pages. This is even more effective with an aggressive cache policy for the js and css, something that can be done without fear thanks to the implemented cache-busting. Also, having then in separate files allows us to use Hugo pipelines for minimizing the code.
		
			
				
	
	
		
			30 lines
		
	
	
		
			841 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			30 lines
		
	
	
		
			841 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
const userPref = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
 | 
						|
const currentTheme = localStorage.getItem('theme') ?? userPref
 | 
						|
 | 
						|
if (currentTheme) {
 | 
						|
  document.documentElement.setAttribute('saved-theme', currentTheme);
 | 
						|
}
 | 
						|
 | 
						|
const switchTheme = (e) => {
 | 
						|
  if (e.target.checked) {
 | 
						|
    document.documentElement.setAttribute('saved-theme', 'dark')
 | 
						|
    localStorage.setItem('theme', 'dark')
 | 
						|
  }
 | 
						|
  else {
 | 
						|
    document.documentElement.setAttribute('saved-theme', 'light')
 | 
						|
    localStorage.setItem('theme', 'light')
 | 
						|
  }
 | 
						|
}
 | 
						|
 | 
						|
window.addEventListener('DOMContentLoaded', () => {
 | 
						|
  // Darkmode toggle
 | 
						|
  const toggleSwitch = document.querySelector('#darkmode-toggle')
 | 
						|
 | 
						|
  // listen for toggle
 | 
						|
  toggleSwitch.addEventListener('change', switchTheme, false)
 | 
						|
 | 
						|
  if (currentTheme === 'dark') {
 | 
						|
    toggleSwitch.checked = true
 | 
						|
  }
 | 
						|
})
 |