技术生活

动态加载favicon图片到页面中

同样的原因,所有的静态资源都要在header中加token才能加载出来,favicon.ico图片也不例外。

具体实现方法:

一、删除<link rel=”shortcut icon” href=”*****” />,动态加载图片并转为base64字符串.

    /*
    References:
        https://base64.guru/developers/javascript/examples/encode-remote-file
        https://base64.guru/converter/encode/image
        http://lab.ejci.net/favico.js/
    */
    function loadImage(url, token, callbackHandler){
        // If you are loading file from a remote server, be sure to configure “Access-Control-Allow-Origin”
        // For example, the following image can be loaded from anywhere
        //var url = '//cdn.static.base64.guru/uploads/images/1x1.gif';

        var imageExtension = url.substr(url.lastIndexOf(".") + 1);
        imageExtension = getImageMediaType(imageExtension);
        var base64ImageHeader = "data:" + imageExtension + ";base64,";
        //data:image/gif;base64,

        // Initialize the XMLHttpRequest and wait until file is loaded
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            // Create a Uint8Array from ArrayBuffer
            var codes = new Uint8Array(xhr.response);

            var bin = "";
            for (var i=0; i<codes.byteLength; i++) {
                bin += String.fromCharCode(codes[i]);
            }
            // Get binary string from UTF-16 code units
            //var bin = String.fromCharCode.apply(null, codes);
            //var bin = Utf8ArrayToStr(codes);
            // Convert binary to Base64
            var base64String = btoa(bin);
            //console.log(base64String); //-> "R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs="
            var src = base64ImageHeader + base64String;
            if(callbackHandler && typeof(callbackHandler) == "function"){
                callbackHandler(src);
            }
        };
        // Send HTTP request and fetch file as ArrayBuffer
        xhr.open('GET', url);
        // For the Fucking IE&Edge browser, this line MUST lay after 'request.open()'
        xhr.responseType = 'arraybuffer';
        // set request header
        xhr.setRequestHeader("x-token", token);
        xhr.send();
    }
    /*
    References:
        https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
    */
    function getImageMediaType(extension){
        var dict = {
            "gif": "image/gif",
            "png": "image/png",
            "jpeg": "image/jpeg",
            "jpg": "image/jpeg",
            "bmp": "image/bmp",
            "ico": "image/vnd.microsoft.icon",
            "svg": "image/svg+xml",
            "tif": "image/tiff",
            "tiff": "image/tiff",
            "webp": "image/webp"
        };
        if(extension in dict){
            return dict[extension];
        } else {
            return "image/" + extension;
        }
    }

    function setFavicon(token){
        //function loadImage(url, token, placehere, newElementId, isHidden, callbackHandler)
        loadImage("static/favicon.png",  token, function(src){
            createFaviconTag(src);
        });
    }

    ...
    <body onload="javascript:setFvicon();">
    ...

二、在head插入诸如这样的标签即可.

    function createFaviconTag(src) {
        if (src) {
            var head = document.head || document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.setAttribute("rel", "shortcut icon");
            link.setAttribute("href", src);
            head.appendChild(link);
        }
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注