• 本地存储组件--兼容IE低版本


        在前端开发过程中,会用到本地缓存,但是由于浏览器对不同规范支持的程度不一样,每次进行使用都要为兼容行花费不少时间。我整理了一个本地存储的组件。
        组件特点:
    • 可以配置使用localStorage、sessionStorage、cookie、Object,IE低版本支持userData
    • 统一的使用接口set、get、remove
    • 使用方便,直接引入JS,进行初始化即可
        下面是源码:
        
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    (function() {
        var ua = navigator.userAgent.toLowerCase();
        var t = ua.match(/msie ([d.]+)/);
        var ie = t && t[1];
        var useUserData = ie ==6 || ie == 7;
      
        var encodeVal = function(value) {
            return encodeURIComponent(value);
            };
      
        var decodeVal = function(value) {
            return decodeURIComponent(value);
            };
      
        var isCookieEnabled = function() {
            if(window.navigator.cookieEnabled) {
                return window.navigator.cookieEnabled;
            }
            var key = 'test_cookie_enable',
                    value = 'test' + Math.random(),
                    result = _cookieStorage.set(key, value);
            if (!result) {
                return false;
            }
            var value2 = _cookieStorage.get(key);
            _cookieStorage.remove(key);
            return value == value2;
        };
      
        var _sessionStorage = {
                get : function(key) {
                    return sessionStorage.getItem(key) || null;
                },
      
                set : function(key, value) {
                    sessionStorage.setItem(key, value);
                },
      
                remove : function(key) {
                    sessionStorage.removeItem(key);
                }
            };
      
        var _localStorage = {
                get : function(key) {
                    return decodeVal(localStorage.getItem(key)) || null;
                },
      
                set : function(key, value) {
                    value = encodeVal(value);
                    localStorage.setItem(key, value);
                },
      
                remove : function(key) {
                    localStorage.removeItem(key);
                }
            };
      
        var _userDataStorage = {
                init: function(maxage) {
                    var memory = document.createElement('input');
                    this.memory = memory;
                    memory.style.display = "none";
                    memory.style.behavior = "url('#default#userData')";
                    document.body.appendChild(memory);
      
                    if(maxage) {
                        var now = +new Date();
                        var expires = now + maxage * 1000;
                        memory.expires = new Date(expires).toUTCString();
                    }
      
                    memory.load('UserDataStorage');
                },
      
                get : function (key) {
                    return decodeVal(this.memory.getAttribute(key)) || null;
                },
      
                set : function(key, value) {
                    value = encodeVal(value);
                    this.memory.setAttribute(key, value);
                    this.memory.save('UserDataStorage');
                },
      
                remove : function(key) {
                    this.memory.removeAttribute(key);
                    this.memory.save('_userDataStorage');
                }
            };
      
        var _cookieStorage = {
                init: function(maxage, path) {
                    this.maxage = maxage;
                    this.path = path;
                },
                set : function(key, value) {
                    var cookie = key + '=' + encodeVal(value);
                    if(this.maxage) cookie += '; max-age=' this.maxage;
                    if(this.path) cookie += '; path=' this.path;
                    document.cookie = cookie;
                },
      
                get : function(key) {
                    var cookies = document.cookie;
                    var reg = new RegExp('(?:^ |)(' + key + ')=([^;]+)');
                    var value = cookies.match(reg);
                    if(value) {
                        return decodeVal(value[2]);
                    }
                    return null
                },
      
                remove : function(key) {
                    this.init(0, '/');
                    this.set(key, '');
                }
            };
      
        var _objectStorage = {
            init : function() {
                this.data = {};
            },
            set : function(key, value) {
                value = encodeVal(value);
                this.data[key] = value;
            },
            get : function (key) {
                return decodeVal(this.data[key]) || null;
            },
            remove : function(key) {
                delete this.data[key];
            }
        };
      
        /**
         * 本地存储
         * @param {String} type 存储类型 [local,session,cookie,page]
         * @param {Number} maxage cookie到期时间 单位秒
         * @param {String} path 路径
         * @return {Object} 具有set、get、remove方法
         */
        function Storage(type, maxage, path) {
            var storage;
            maxage = maxage || '';
            path = path || '/';
            type = type || 'local';
      
            switch (type) {
                case 'local' :
                    try // 禁用cookie、localStorage时访问会报错
                        storage = window.localStorage ? _localStorage : useUserData ? _userDataStorage : Object;
                    catch (e) {
                        storage = _objectStorage;
                    }
                    break;
                case 'session' :
                    try // 禁用cookie、_localStorage时访问会报错
                        storage = window.sessionStorage ? _sessionStorage : _objectStorage;
                    catch (e) {
                        storage = _objectStorage;
                    }
                    break;
                case 'cookie' :
                    storage = isCookieEnabled() ? _cookieStorage : _objectStorage;
                    break;
                case 'page' :
                    storage = _objectStorage;
            }
            storage.init && storage.init(maxage, path);
            return storage;
        }
      
        window.Storage = Storage;
    })();
     
        
      使用例子:
      
    1
    2
    3
    4
    5
    6
    7
    var storage = new Storage('local');
        storage.set('name''中国人');
        var name = storage.get('name');
        alert(name);
        storage.remove('name');
        var name = storage.get('name');
        alert(name);
      如果觉得有用可以推荐一下,那里实现的有问题,也希望指正。
        
  • 相关阅读:
    记录上锁(字节范围锁,特例:锁住文件的某一部分或者整个文件)
    读写锁的实现原理(pthread_rwlock_t)
    Linux 互斥锁的实现原理(pthread_mutex_t)
    System V消息队列
    Web安全之SQL注入攻击技巧与防范
    如何正确地写出单例模式
    java的concurrent用法详解
    java并发编程-Executor框架
    java.util.concurrent包分类结构图
    Java多线程干货系列(1):Java多线程基础
  • 原文地址:https://www.cnblogs.com/jijm123/p/8433866.html
Copyright © 2020-2023  润新知