google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






La mise en cache JavaScript dans HTML5 Chaque d?veloppeur web/programmeur web programmeur web/devrait conna?tre l'importance de la mise en cache JavaScript pour des performances Web Avec des sp?cifications techniques des versions HTML vieux, nous ne pouvons stocker les caches du navigateur JavaScript dans cookie sur le c?t? client, ou le faire sur le c?t? serveur avec la session/autres solutions de stockage avec des fichiers web
HOT nouvelles API JavaScript avec HTML5 ), HTML5 aussi nous donner les capacit?s de stockage local pour acc?l?rer le performance.


Gratuit iPage hébergement Web pour la première année MOMENT



Si vous êtes toujours à la recherche d'un fournisseur d'hébergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Crédits supplémentaires gratuites pour le paiement de 24 mois ($45)?

Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'êtes pas aussi! Plus important encore, lorsque vous enregistrez l'hébergement web à iPage grâce à notre lien, nous allons être heureux de renvoyer un plein remboursement. C'est génial! Vous devriez essayer iPage hébergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
Essayez iPage GRATUIT première année MOMENT

Every developer knows the importance of caching. From end to end you have caching on the backend (memcached, xcache, etc.) to prevent your databases being lit on fire, edge caching on content delivery networks (CDN's) in hopes that your browser will cache assets it sees more than once. And of course client-side caching so you don't repeat expensive operations (albeit algorithmically or high volume repitions). Here is a solution in JavaScript to help you out with the latter, with optional support for HTML5 Local Storage.

Starting Simple

function CacheProvider() {
  // values will be stored here
  this._cache = {};
}

Feature detect on local storage

try {
  CacheProvider.hasLocalStorage = ('localStorage' in window) && window['localStorage'] !== null;
} catch (ex) {
  CacheProvider.hasLocalStorage = false;
}

The main reason we use try / catch is because despite Firefox supporting it, it can be disabled in your about:config settings and an error will be thrown. A simple if / else will not work.

Next we'll add support for storing objects into local storage. This technique was borrowed from Christopher Blizzard in his excellent post Saving data with local storage - for which those who didn't know, you can only store string's into local storage. Thus we have this...

in / out JSON parsing

if (CacheProvider.hasLocalStorage) {
  Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
  };

  Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
  };
}

Now for our three core methods, we'll have get, set, and clear.

Core class functionality

CacheProvider.prototype = {

  /**
     * {String} k - the key
     * {Boolean} local - get this from local storage?
     * {Boolean} o - is the value you put in local storage an object?
     */
  get: function(k, local, o) {
    if (local && CacheProvider.hasLocalStorage) {
      var action = o ? 'getObject' : 'getItem';
      return localStorage[action](k) || undefined;
    } else {
      return this._cache[k] || undefined;
    }
  },

  /**
     * {String} k - the key
     * {Object} v - any kind of value you want to store
     * however only objects and strings are allowed in local storage
     * {Boolean} local - put this in local storage
     */
  set: function(k, v, local) {
    if (local && CacheProvider.hasLocalStorage) {
      if (typeof v !== 'string') {
        // make assumption if it's not a string, then we're storing an object
        localStorage.setObject(k, v);
      } else {
        try {
          localStorage.setItem(k, v);
        } catch (ex) {
          if (ex.name == 'QUOTA_EXCEEDED_ERR') {
            // developer needs to figure out what to start invalidating
            throw new Exception(v);
            return;
          }
        }
      }
    } else {
      // put in our local object
      this._cache[k] = v;
    }
    // return our newly cached item
    return v;
  },

  /**
     * {String} k - the key
     * {Boolean} local - put this in local storage
     * {Boolean} o - is this an object you want to put in local storage?
     */
  clear: function(k, local, o) {
    if (local && CacheProvider.hasLocalStorage) {
      localStorage.removeItem(k);
    }
    // delete in both caches - doesn't hurt.
    delete this._cache[k];
  }

};

How does this work?

Note in the beginning of this post, said Cache Provider was to have optional support for local storage (although it appears to be most of the point). First let's look at an example sans-local-storage.

getElementsByClassName

var cache = new CacheProvider;

window.getElementsByClassName = getElementsByClassName || function(c) {
  var reg = cache.get(c) || cache.set(c, new RegExp("(?:^|\\s+)" + c + "(?:\\s+|$)"));
  var elements = document.getElementsByTagName('*');
  var results = [];
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].className.match(reg)) {
      results.push(elements[i]);
    }
  }
  return results;
};

Note the next time you work with the same class - it work with a precompiled regular expression instead of constructing a new one.

As another example, for large apps that require i18n, you could cache the compiled HTML strings into local storage.

var i18nCache = new CacheProvider;

if (i18nCache.get('topnav')) {
  $('#nav').html(i18nCache.get('topnav'));
} else {
  ajax('top-nav.tmpl', function(html) {
    i18nCache.set('topnav', html);
    $('#nav').html(i18nCache.get('topnav'));
  });
}

Other than that, have a play, do some caching, and outsource your resources to your users browser. cheers ;)

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web