最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to create a favicon in javascript? - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 11:51 CommunityBot 11 silver badge asked Oct 9, 2012 at 22:08 BengtBengt 14.5k7 gold badges52 silver badges67 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论