Basket.js 使用 localStorage 缓存网页脚本文件

发布于 2018-07-08 19:19:00 字数 9068 浏览 3298 评论 0

简单来说 Basket.js 是一个脚本缓存器,使用本地储存 localStorage 缓存 JavaScript 文件,如果脚本以前在本地缓存过,那么他将会被快速的加载到页面中,如果没有缓存过,那么久使用 XHR 异步加载到页面中。

通过 Google 和 Bing 大量的测试表明,使用 localStorage 本地储存要比直接使用浏览器缓存在性能上有很多提升。

HTML5 规范建议存储限额为 5MB 的本地存储,但浏览器可以实现他们自己的配额,如果他们希望。如果超出了配额,浏览器可能无法在缓存中存储项目。如果发生这种情况,Bask.js 将从最旧的缓存中删除条目,然后重试。有些像 Opera 这样的浏览器会要求用户在超过设定阈值时增加配额。

释放空间 Base.js 将只删除在本地存储本身中放置的缓存脚本。其他代码存储在同一原点的数据将不会被触摸。

API

  • basket.require()
  • basket.get()
  • basket.remove()
  • basket.clear()

basket.require

basket.require(details)

details: Either an object or an array of objects with the following fields:

  • url (required) The URI for the script. At present this must be a URI on the same origin as the caller.
  • key The name that will be used to refer to this script. By default this is the uri.
  • expire How long (in hours) before the cached item expires.
  • execute Whether to cause the script to be executed once it has been retrieved. Defaults to true.
  • unique A token stored with the cached item. If you request the same item again with a different token the script will be fetched and cached again.
  • skipCache Prevent storing the script in cache. Useful when you want load scripts in order, but only cache some. By default is false.

require() returns a promise that will be fulfilled when each of the requested items has been fetched, or rejected if any item fails.

Examples

Single script

basket.require({ url: 'jquery.js' });

This fetches a single script and executes it. If the script was already in the localStorage cache it will be loaded from there, otherwise it will be loaded from the network. The script will then be injected into the document for the browser to execute.

Multiple scripts

basket.require(
    { url: 'jquery.js' },
    { url: 'underscore.js' },
    { url: 'backbone.js' }
);

Multiple scripts will be requested. The scripts are requested asynchronously but executed in the same order as specified.

Multiple scripts without caching some of them

basket.require(
    { url: 'require.js' },
    { url: 'require.config.js', skipCache: true },
    { url: 'libs.js' }
);

Multiple scripts will be requested. require.config.js will not be cached in localStorage. Useful if order of scripts execution is important but storing certain script is not needed, e.g. it changes with each request.

Ordering dependencies

basket
    .require({ url: 'jquery.js' })
    .then(function () {
        basket.require({ url: 'jquery-ui.js' });
    });

Here we ask basket.js to load jQuery. Once it has been fetched and executed, the promise returned by require() will be fulfilled and the callback passed to the then() method of the promise will be executed. Now we can do anything the requires jquery to be loaded including load any scripts that depend on it.

Error handling

basket
    .require({ url: 'missing.js' })
    .then(function () {
        // Success
    }, function (error) {
        // There was an error fetching the script
        console.log(error);
    });

The second parameter to then() is a function that will be called if the promise is rejected. That is, if there was an error fetching the script. The only parameter to the error callback will be an Error object with details of the failure.

Using an alias

basket.require({ url: 'jquery-2.0.0.min.js', key: 'jquery' });

If you wish to store a script under a specific key name (e.g. if you have a build process which creates a script with a name like 012345.js and want to store it as, say, main), you can set the key property to the name you want to use.

This can also be useful for libraries with version numbers in their URIs when you don't need a particular version. In the above example the cache will be checked for a script stored as "jquery" regardless of its original URI. This allows us to use an older version stored in the cache if one exists.

If key is not set the url will be used instead.

Cache expiry

basket.require({ url: 'jquery.min.js', expire: 2 })

Here script will only be cached for up to 2 hours. After that time it will be fetched from the network again even if it exists in the cache. To re-fetch after 7 days you could set 168 ( i.e. 7 * 24 = 168 ).

If expire is not set, the default time of 5000 hours will be used - almost 7 months.

Cache a file without executing it

basket.require({ url: 'jquery.min.js', execute: false });

The script will be cached but will not be added to the document to be executed.

Cache busting

// fetch and cache the file
basket.require({ url: 'jquery.min.js' });
// fetch and cache again
basket.require({ url: 'jquery.min.js', unique: 123 });

Set the unique property to control whether the script will be loaded from the cache. If the parameter is different in the request to that stored in the cache the file is fetched again.

basket.js will add the "basket-unique" parameter on to the url to also prevent the script being fetched from the browser cache.

basket.get

basket.get(key)

key The key to lookup in the localStorage cache.

get() will return an object if script is found or false if not. The object contains the same data as that passed to require() when it was first loaded, with some additional details added:

  • stamp The timestamp for when the file was fetched.
  • expire The timestamp for when the item will expire.
  • data The file contents of the script.
var req
var ttl;

basket.require({ url: 'jquery.min.js', key: 'jquery' });
req = basket.get('jquery');
// know the lifetime
ttl = req.expire - req.stamp;

basket.remove

basket.remove(key)

key The key to remove from the localStorage cache.

remove() will simply remove a previously cached script from localStorage. An example of how to use it can be seen below:

basket
    .remove('jquery.js')
    .remove('modernizr');

basket.clear

basket.clear(expired)

expired If expired is true then only items that have expired will be removed. Otherwise all items are removed.

clear() removes items from the cache.

basket.clear();
basket.clear(true);

basket.isValidItem

basket.isValidItem(source, obj)

  • source The source of the item returned from localStorage
  • obj The item passed into require

Optional This property can be set to a custom validation method that should return a boolean value depending on the validity of the item (source). isValidItem is called for each item in a require call.

isValidItem() is expected to return true is the item is valid. If isValidItem() returns false, the item will be loaded from the network. isValidItem() if present is an additonal check and does not override the existing checks for expiration and uniqueness.

This is targetted at advanced usage and is strictly optional. The use of unique and expire parameters are the most appropriate way to handle common scenarios.

basket.isValidItem = function (source, obj) {
    return myVerificationFunction(source, obj);
};

相关链接

项目地址:https://addyosmani.com/basket.js/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84960 人气
更多

推荐作者

遂心如意

文章 0 评论 0

5513090242

文章 0 评论 0

巷雨优美回忆

文章 0 评论 0

junpengz2000

文章 0 评论 0

13郎

文章 0 评论 0

qq_xU4RDg

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文