Changing website favicon dynamically

javascript

You can change the website favicon dynamically using JavaScript by manipulating the link element in the HTML head that references the favicon.

Here’s an example code snippet:

// Create a new link element for the new favicon
var newFavicon = document.createElement('link');
newFavicon.rel = 'shortcut icon';
newFavicon.type = 'image/png';
newFavicon.href = 'new-favicon.png';

// Get the current favicon link element from the HTML head
var oldFavicon = document.querySelector('link[rel="shortcut icon"]');

// Replace the old favicon with the new one
document.head.replaceChild(newFavicon, oldFavicon);

In this example, a new link element is created with the desired attributes for the new favicon. The href attribute is set to the path of the new favicon image file.

The current favicon link element is then selected using the querySelector method, which matches the rel attribute with the value of shortcut icon. Note that if there are multiple link elements with the rel attribute set to shortcut icon, this method will only select the first one.

Finally, the replaceChild method is used to replace the old favicon link element with the new one. This updates the favicon displayed in the browser tab.

Note that changing the favicon dynamically using JavaScript can cause a brief flash or delay in the favicon display, depending on the browser and network conditions.