8

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.

Community
  • 1
  • 1
Bengt
  • 14,011
  • 7
  • 48
  • 66

1 Answers1

11

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.

Community
  • 1
  • 1
Bengt
  • 14,011
  • 7
  • 48
  • 66
  • 5
    @jrd1: Yes, it's called sharing knowledge. Check the ["Ask Question"](http://stackoverflow.com/questions/ask) page. – Bengt Oct 09 '12 at 22:32
  • @Deadalus: I asked for the best way to do this. This solution only works for simple graphics and IE>=9. I extended/clarified my question and answer. – Bengt Oct 09 '12 at 22:33
  • @bngtlrs, agreed. I meant no offense by it. When I posted that, you hadn't updated your question to reflect your answer. Hence, my incredulous comment. – jrd1 Oct 09 '12 at 22:40
  • @jrd, none taken. I did this "Q&A at once" before and irritated people by it, but sometimes it seems the right tool for collecting knowledge. Perhaps I should be more cautious to clarify what I do and want by it – Bengt Oct 09 '12 at 22:54