Isn't it silly that a tiny favicon requires yet another HTTP request? How can I put the favicon into a sprite?

后端 未结 14 1790
暖寄归人
暖寄归人 2020-11-29 14:58

Everybody knows how to set up a favicon.ico link in HTML:



        
14条回答
  •  执笔经年
    2020-11-29 15:05

    A minor improvement to @yc's answer is injecting the base64-encoded favicon from a JavaScript file that would normally be used and cached anyway, and also suppressing the standard browser behavior of requesting favicon.ico by feeding it a data URI in the relevant meta tag.

    This technique avoids the extra http request and is confirmed to work in recent versions of Chrome, Firefox and Opera on Windows 7. However it doesn't appear to work in Internet Explorer 9 at least.

    index.html

    
    
        
            
            
            
            
    ...
    

    script.js

    var favIcon = "\
    iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABrUlEQVR42mNkwAOepOgxMTD9mwhk\
    [...truncated for brevity...]
    IALgNIBUQBUDAFi2whGNUZ3eAAAAAElFTkSuQmCC";
    
    var docHead = document.getElementsByTagName('head')[0];       
    var newLink = document.createElement('link');
    newLink.rel = 'shortcut icon';
    newLink.href = 'data:image/png;base64,'+favIcon;
    docHead.appendChild(newLink);
    
    /* Other JS would normally be in here too. */
    

    Demo: turi.co/up/favicon.html

提交回复
热议问题