google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






JavaScript và Cache trong HTML5 Mọi nhà phát triển/lập trình web đều biết tầm quan trọng của cache đối với hiệu suất hoạt động của trang web; với đặc tả kĩ thuật của các chuẩn HTML cũ, chúng ta chỉ có thể lưu cache trong cookie ở phía máy khách hoặc thực hiện ở phía máy chủ với session và/hoặc các biện pháp lưu trữ dạng tệp tin.

Nhưng mới HTML5, ngoài khả năng lưu trữ cache để xem ngoại tuyến (xem thêm nhiều tính năng khác của HTML5 tại Các hàm JavaScript mới trong HTML5); công nghệ mới này còn cho phép các nhà phát triển web xây dựng các ứng dụng web có thể lưu cache ở phía máy khách nhằm cải thiện hiệu suất hoạt động của trang web, bởi trình duyệt sẽ gửi ít truy vấn hơn đến máy chủ mỗi khi tải một trang web trong hệ thống website.

Bài viết này sẽ cung cấp cho bạn vài khái niệm cơ bản và ví dụ mẫu JavaScript để xây dựng tính năng cache trong HTML5. Vui lòng vào trang chi tiết để xem thêm.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

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 theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web