Chapter 7, Exercise 5 – Local Storage Polyfill

Write a polyfill to add Local Storage support to older browsers using cookies. You’ll need to create an object called window.localStorage, if one doesn’t already exist, and create getItem and setItem methods.

Make a new file called local-storage.js in the _js folder and place the following in it:

(function(){
  window.localStorage = {
    setItem: function (name, value) {
      alert(name + " " + value);
      var date = new Date();
      date.setTime(date.getTime() + 10 * 365 * 24 * 60 * 60 * 1000)
      var expires = "expires=" + date.toUTCString();
      document.cookie = name + "=" + value + "; " + expires;
    },
    getItem: function (name) {
      var name = name + "=";
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
      }
      return "";
    }
  }
})();

We’re only creating two methods of localStorage: the setItem and getItem calls, so this isn’t a great polyfill. The contents of setItem and getItem are fairly standard cookie setting and getting code, and the cookie expiry is set to ten years into the future – which is probably longer than anyone will still be playing this version of Bubble Shooter, at least without setting a new high score.

We only want to load it into the game if Local Storage isn’t already supported, and we can do this with a test in the Modernizr.load call:

 {
    test: Modernizr.canvas,
    yep: ["_js/renderer.js","_js/sprite.js"]
  },
  {
    test: window.localStorage,
    nope: "_js/local-storage.js"
  },
 {
  load : "_js/game.js",
  complete: function(){
    $(function(){
      var game = new BubbleShoot.Game();
      game.init();
    })
}
}];

We only load the file in if window.localStorage doesn’t already exist.

Leave a Reply