Multiple base64 files in one

后端 未结 7 897
不知归路
不知归路 2021-01-16 08:29

Can you combine these 2 images into one external file on this JS fiddle and link to them as images?

Something like



        
7条回答
  •  别那么骄傲
    2021-01-16 09:00

    From what I understand, you wish to cache various type of resources (like a font, an image, etc.) using a single HTTP request.

    So, here's my take on this using jQuery (you may opt for using vanilla JavaScript):

    Firstly, you can store all your data-to-cache as string or Boolean or Number in a Associative Array in JavaScript and load this single file as shown below.

    var ResourceLibrary = [];
    ResourceLibrary["hello"] = "Hello World!";
    ResourceLibrary["genderMale"] = true;
    ResourceLibrary["username"] = "srvikram13";
    ResourceLibrary["isDeveloper"] = true;
    ResourceLibrary["firefox"] = "data:image/png;base64,iVBORw0KG...."
    ResourceLibrary["chrome"] = "data:image/png;base64,iVBORw0KG...."
    

    Now for every element that you wish to apply the cache data, you can give a custom attribute say-data-src as shown below.

    firefox
    chrome
    



    Male
    Developer

    Now on document.ready (or onload if using vanilla JS) just loop through each element with this custom attribute; and apply the cached value based on the corresponding resourceId.

    $(document).ready(function(){
        $("*").each(function(i, e){
            if($(e).attr("data-src") && $(e).attr("data-src").indexOf("resourceId-") != -1) {
                switch($(e).get(0).tagName) { // Add more case statements to handle various types of elements
                    case "INPUT" : 
                        if(!$(e).attr("type")){
                            $(e).val(ResourceLibrary[$(e).attr("data-src").replace("resourceId-", "")]);
                            return;
                        }
                        switch($(e).attr("type").toLowerCase()) {
                            case "radio":
                            case "checkbox":
                                $(e).attr("checked", ResourceLibrary[$(e).attr("data-src").replace("resourceId-", "")])
                        }
                        return;
                    case "IMG" :
                        $(e).attr("src", ResourceLibrary[$(e).attr("data-src").replace("resourceId-", "")]);
                        return;
                    case "P" :
                        $(e).html(ResourceLibrary[$(e).attr("data-src").replace("resourceId-", "")]);
                       return;
                    default:
                       return;
                }
            }
        });
    });
    

    Working Demo

提交回复
热议问题