Search code examples
javascripthtmlhtml5-canvasfavicon

How to create a favicon in javascript?


I want to add a favicon to a website to be able to identify it's tab. I do not want the favicon to be a file, though. What is the best way to create one in Javascript?

Reasons

  • A favicon file requires an additional HTTP request which increases the page load time.
  • Changing the web server might change static content serving to another fashion, which causes headaches.

PS: I have presented a solution as an answer to this, but I wonder if there is a better way.


Solution

  • If simple, form based graphics suffice, one can use HTML5 Canvas to create a favicon. There have been successful attempts to modify a favicon image after loading it. Analogously one can create a favicon entirely in javascript using the basic canvas API. The following example creates and sets a grey favicon with a green square on it:

    <script>
        var canvas = document.createElement('canvas');
        canvas.width = 16;
        canvas.height = 16;
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = "#aaa";
        ctx.fillRect(0, 0, 16, 16);
        ctx.fillStyle = "#afa";
        ctx.fillRect(4, 4, 8, 8);            
        var link = document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = canvas.toDataURL("image/x-icon");
        document.getElementsByTagName('head')[0].appendChild(link);
    </script>
    

    For currently outdated versions Internet Explorer (<9) one needs a workaround like Explorer Canvas. See the official instructions on how to do that.