Dynamically Updating Website Favicon
In a web application where branding is customized based on the user, dynamically changing the page favicon to reflect the private label's logo becomes imperative. However, finding code or examples to achieve this can be challenging.
One potential solution involves storing a collection of icons in a folder and dynamically generating the reference to the appropriate favicon.ico file alongside the HTML page.
Using JavaScript
To dynamically update the favicon, you can utilize JavaScript:
var link = document.querySelector("link[rel~='icon']"); if (!link) { link = document.createElement('link'); link.rel = 'icon'; document.head.appendChild(link); } link.href = 'https://stackoverflow.com/favicon.ico';
This code selects the element with the rel attribute set to icon using the querySelector method. If no such element exists, it creates a new element, sets the rel attribute to icon, then appends it to the document's
. Finally, the href attribute is updated with the desired favicon path.By incorporating this code into your web application, you can effortlessly update the favicon based on user-specific branding, allowing for a cohesive and personalized online experience.
The above is the detailed content of How Can I Dynamically Update a Website's Favicon with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!