[JavaScript] Load Favicon Dynamically

This post is an extension of reference [1], which discusses how to load external JavaScript or CSS dynamically. The same idea can be applied to load favicon dynamically. Give the URL or path of favicon to the following function, and then favicon will be loaded dynamically:

function LoadFavicon(url) {
  var ext = document.createElement('link');
  ext.setAttribute("rel", "shortcut icon");
  ext.setAttribute("href", url);

Example Usage of LoadFavicon Function

Assume that the path of favicon is located at /favicon.ico under the domain of the website. You can call:


to load favicon dynamically. Even if your favicon is located at a different domain, you can still pass the URL of favicon at the different domain to above function and it also works!



[1]Load External JavaScript or CSS file Dynamically