3 ms·
Seems like a helpful list of things to know, I haven't gone through it all but looks good so far. Clicked on the first one and I noticed something. They write
by flanbiscuit 3y ago
Seems like a helpful list of things to know, I haven't gone through it all but looks good so far.
Clicked on the first one and I noticed something.
They write this:
const setFavicon = () => {
const favicon = document.querySelector('link[rel="icon"]');
favicon.href = (window.matchMedia('(prefers-color-scheme: dark)').matches)
? 'dark-mode-favicon.png'
: 'light-mode-favicon.png';
};
setFavicon();
And then this:
> We can use this function to update the user's color scheme preference whenever they make a change.
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', setFavicon);
They are running "window.matchMedia('(prefers-color-scheme: dark)')" twice unnecessarily. If you're going to run `setFavicon` as the callback to the event listener, you can get the result from the `event` parameter passed to the callback like this:
const setFavicon = (event) => {
const favicon = document.querySelector('link[rel="icon"]');
favicon.href = event.matches ? 'dark-mode-favicon.png' : 'light-mode-favicon.png';
This would be my preferred way of doing it because it supports users who are visiting with JS disabled.
<link href="light-mode-favicon.png" rel="icon" media="(prefers-color-scheme: light)">
<link href="dark-mode-favicon.png" rel="icon" media="(prefers-color-scheme: dark)">
https://phuoc.ng/collection/html-dom/change-the-favicon-dynamically-based-on-user-color-scheme-preference/ https://phuoc.ng/collection/html-dom/change-the-favicon-dyna...
- explaininjs 3y agoAlso, doing it in HTML prevents the flash of alternate-themed content. Doing the same with the `theme-color` meta is also a seldom-used but great feature for detail-minded PWA developers.