javascript 如何使用/创建 MANIFEST、处理 appCache 事件/错误以及使用 swapCache

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20045643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:34:01  来源:igfitidea点击:

How to use/create a MANIFEST, handle appCache events/errors and the use of swapCache

javascripteventshtml5-appcachecache-manifestapplication-cache

提问by Aleksander Azizi

How do you use and create a MANIFEST file (structure),

你如何使用和创建一个MANIFEST文件(结构),

handle appCache events and errors,

处理 appCache 事件和错误,

and when is swapCache needed?

什么时候需要交换缓存?

回答by Aleksander Azizi

Use Application Cache With Manifest

将应用程序缓存与清单一起使用

To use application cache you need to reference to the manifest file inside the HTML document, like this:

要使用应用程序缓存,您需要引用 HTML 文档中的清单文件,如下所示:

<html manifest="manifest.appcache"/>

The manifest file itself needs a predetermined layout to work.

清单文件本身需要预先确定的布局才能工作。

CACHE MANIFESTis mandatory, and needs to be at the top (so that when the browser checks if it is a cache manifest, it returns true).

CACHE MANIFEST是强制性的,需要在顶部(这样当浏览器检查它是否是缓存清单时,它返回真)。

CACHEis optional, but recommended, and used for referring to the files you want cached locally.

CACHE是可选的,但推荐使用,用于引用您要在本地缓存的文件。

FALLBACKis optional, and is used to specify file(s) that should be used if the specified one (in CAHCE) is unavailable. The first file specified (in FALLBACK) is the original file, and the second file is the one that will be used if the original file is unavailable.

FALLBACK是可选的,用于指定在指定的文件 (in CAHCE) 不可用时应使用的文件。指定的第一个文件 (in FALLBACK) 是原始文件,第二个文件是原始文件不可用时使用的文件。

NETWORKshould be considered to be mandatory, but isn't. It is used to specify what files needs an internet connection (isn't cached). Using "*" (without the brackets) specifies that all other files except the ones mentioned in CACHE, needs an active internet connection.

NETWORK应该被认为是强制性的,但不是。它用于指定哪些文件需要 Internet 连接(未缓存)。使用“*”(不带括号)指定除 中提到的文件之外的所有其他文件都CACHE需要有效的 Internet 连接。

Example:

例子:

CACHE MANIFEST

CACHE:
YourFirstFile.html
YourSecondFile.png
fallbackFile1.html
fallbackFile2.png
Etc.css

FALLBACK:
YourFirstFile.html fallbackFile1.html
YourSecondFile.png fallbackFile2.png

NETWORK:
*

The manifest (and its specified resources) is only checked upon page load (when the user enters the site). Side note: The manifest file iscase sensitive.

清单(及其指定的资源)仅在页面加载时(当用户进入站点时)进行检查。附注:清单文件区分大小写的。



Handling events triggered in application cache

处理应用程序缓存中触发的事件

The first thing I want to say is appCacheis really window.applicationCache, so it needs to be declared (var appCache = window.applicationCache;).

我想说的第一件事appCache是真的window.applicationCache,所以需要声明 ( var appCache = window.applicationCache;)。

When a user enters the site for the first time (or the manifest cache isn't present), the following events are triggered; if everything works as it should:

当用户第一次进入站点(或清单缓存不存在)时,将触发以下事件;如果一切正常:

Creating Application Cache with manifest

Application Cache Checking

Application Cache Downloading

Application Cache Progress (0 of X)

Application Cache Cached

使用清单创建应用程序缓存

应用缓存检查

应用缓存下载

应用程序缓存进度(X 中的 0)

缓存应用程序缓存

Let's break it down.

让我们分解一下。

The first (Creating Application Cache) specifies a cache “file/folder” for the browser to use later on.

第一个 ( Creating Application Cache) 指定浏览器稍后使用的缓存“文件/文件夹”。

The second (Application Cache Checking) "checking", looks inside the manifest file to see what it needs to cache.

第二个 ( Application Cache Checking) " checking",查看清单文件以查看它需要缓存的内容。

The third (Application Cache Downloading) "downloading", begins the download process of the files specified in the manifest.

第三个 ( Application Cache Downloading) " downloading" 开始下载清单中指定的文件。

The fourth (Application Cache Progress) "progress", keeps track of the downloading progress (this is triggered for each file).

第四个 ( Application Cache Progress) " progress",跟踪下载进度(这是为每个文件触发的)。

The fifth (Application Cache Cached) "cached", simply says “i'm done” caching the files, and everything went as it should.

第五个 ( Application Cache Cached) " cached",简单地说“我已经完成了”缓存文件,一切都按预期进行。

What does this mean? It means that we can have some control over the events, and can trigger our own events if we'd like to.

这是什么意思?这意味着我们可以对事件进行一些控制,并且可以根据需要触发我们自己的事件。

So by listening to the progressevent, we can display a progress bar, a notification with steps or really whatever we want.

因此,通过侦听progress事件,我们可以显示进度条、带有步骤的通知或我们想要的任何内容。

appCache.addEventListener("progress", function(event) {
    console.log(event.loaded + " of " + event.total);
}, false);

Wait, what did I just do?

等等,我刚刚做了什么?

I added an event listenerwith an anonymous-function. Within this function I pass on an “event” from what we are listening to (downloading), and simply loggedhow many files has been cached thus far and how many files there are in total.

我添加了event listener一个匿名函数。在这个函数中,我传递了一个我们正在监听的“事件”(downloading),以及logged到目前为止缓存了多少文件以及总共有多少文件。

Let's do this on all the events mentioned, from the first called event, to the last:

让我们对提到的所有事件执行此操作,从第一个调用的事件到最后一个:

appCache.addEventListener("checking", function(event) {
    console.log("Checking for updates.");
}, false);


appCache.addEventListener("downloading", function(event) {
    console.log("Started Download.");
}, false);


appCache.addEventListener("progress", function(event) {
    console.log(event.loaded + " of " + event.total + " downloaded.");
}, false);

appCache.addEventListener("cached", function(event) {
    console.log("Done.");
}, false);

Now these events do what I want them to.

现在这些事件做我想让他们做的。

These are the appCache events:

这些是 appCache 事件:

checking- Always the first event triggered. Checks for an update in the manifest.

checking- 总是第一个触发的事件。检查清单中的更新。

downloading- Triggered when an update is found. Downloads resources specified in the manifest.

downloading- 发现更新时触发。下载清单中指定的资源。

progress- Triggered for each resource currently downloading. Tracks the progress (by file).

progress- 针对当前下载的每个资源触发。跟踪进度(按文件)。

error- Triggered if 404, 410 network error occurs, or the manifest file was changed while downloading.

error- 如果发生 404、410 网络错误,或者在下载时更改清单文件,则会触发。

obsolete- Triggered if 404, 410 network error occurs, or the manifest file doesn't exist (on the server). Note that this event will delete previous (and current) application cache.

obsolete- 如果发生 404、410 网络错误,或清单文件不存在(在服务器上),则触发。请注意,此事件将删除以前(和当前)的应用程序缓存。

cached- (Only) Triggered the first time the resources specified in the manifest is cached.

cached- (仅)第一次缓存清单中指定的资源时触发。

noupdate- Triggered if no change has been made to the manifest since the last cache update.

noupdate- 如果自上次缓存更新以来未对清单进行任何更改,则触发。

updateready- Triggered if new resources are downloaded.

updateready- 下载新资源时触发。



Scenario handling (error(s), events and triggers)

场景处理(错误、事件和触发器)

What if something goes wrong? We can handle that with errorand/or obsolete.

如果出现问题怎么办?我们可以使用error和/或来处理obsolete

erroris triggered when something goes wrong while updating.

error更新时出现问题时触发。

e.g.

例如

  • A file specified in the manifest does not exist on the server.
  • The manifest is changed while downloading.
  • 服务器上不存在清单中指定的文件。
  • 下载时清单已更改。

obsoleteis triggered when the manifest file doesn't exist (on the server).

obsolete当清单文件不存在(在服务器上)时触发。

e.g.

例如

  • The manifest file is deleted from the server.
  • The website points to an invalid url/path (<html manifest="manifest.appcache"/>).
  • 从服务器中删除清单文件。
  • 该网站指向无效的 url/路径 ( <html manifest="manifest.appcache"/>)。

By listening to error, we can, for example, tell the user if something goes wrong:

error例如,通过聆听,我们可以告诉用户是否出现问题:

appCache.addEventListener("error", function(event) {
    if (navigator.onLine == true) { //If the user is connected to the internet.
        alert("Error - Please contact the website administrator if this problem consists.");
    } else {
        alert("You aren't connected to the internet. Some things might not be available.");
    }
}, false);

Here I checked if the user have an active internet connection or not. Keep in mind that this is just an example, telling the user might not be necessary (depending on your website).

在这里,我检查了用户是否有活动的互联网连接。请记住,这只是一个示例,告诉用户可能没有必要(取决于您的网站)。

We can do the same thing with obsolete, but we might not want to tell the user about it, as this is a server side problem:

我们可以用 做同样的事情obsolete,但我们可能不想告诉用户它,因为这是一个服务器端问题:

appCache.addEventListener("obsolete", function(event) {
    console.log("Obsolete - no resources are cached, and previous cache(s) are now deleted.");
}, false);


swapCache

交换缓存

Now this is a tricky one. The main questions about swapCacheis; "What does it do?", "Is it useful/needed?" and "Should it be used?".

现在这是一个棘手的问题。关于的主要问题swapCache是;“它有什么作用?”,“它有用/需要吗?” 和“应该使用它吗?”。

swapCacheis used to replace the old cache with the new one. It can only be used inside the updatereadyevent (if used elsewhere, it will throwback an error).

swapCache用于用新缓存替换旧缓存。只能在updateready事件内部使用(如果在其他地方使用,会抛出错误)。

"What does it do?": swapCache does what it says, swaps the current cache with a new one.

“它做什么?”:swapCache 做它所说的,将当前缓存与新缓存交换。

"Is it useful/needed?": appCache is useful, the main reason to use it would be to make sure the newsiest cache available is used. Altho this seems like a thing that should work by itself, that's not always the case. For example, some browsers don't always use the latest cache as haven't gotten the message that it needs to (the iPhone is a good example ). An image might be cached, then deleted/renamed, then cached, and so on. In the end, the browser might use an old cache to display that image because of the reference it already has with the stored caches(s). Bottom line: Is it useful? yes. Is it needed? no.

“它有用/需要吗?”:appCache 很有用,使用它的主要原因是确保使用最新可用的缓存。尽管这似乎是一件应该自己工作的事情,但情况并非总是如此。例如,一些浏览器并不总是使用最新的缓存,因为没有收到它需要的消息(iPhone 就是一个很好的例子)。图像可能会被缓存,然后被删除/重命名,然后被缓存,等等。最后,浏览器可能会使用旧缓存来显示该图像,因为它已经对存储的缓存进行了引用。底线:有用吗?是的。需要吗?不。

"Should it be used?": Personally I would say yes. But it depends on what your page does. If the criteria from the example above matches your resource handling, then yes. Otherwise it wouldn't really matter.

“应该使用它吗?”:我个人会说是。但这取决于您的页面做什么。如果上例中的条件与您的资源处理相匹配,则是。否则真的无所谓。

so by adding an event listener to updateready, we can include swapCache:

因此,通过向 中添加事件侦听器updateready,我们可以包含 swapCache:

appCache.addEventListener("updateready", function(event) {
    appCache.swapCache();
    window.reload();
}, false);


(appCache) Event variables:

(appCache) 事件变量:

progress.
         total 
         loaded 
         lengthComputable
GENERAL (for all):
         clipboardData
         cancelBubble
         returnValue
         srcElement
         defaultPrevented
         timeStamp
         cancelable
         bubbles
         eventPhase
         currentTarget
         target
         type
         stopPropagation
         preventDefault
         initEvent
         stopImmediatePropagation


Nice external pages:

漂亮的外部页面:

http://www.html5rocks.com/en/tutorials/appcache/beginner/- appCache basics.

http://www.html5rocks.com/en/tutorials/appcache/beginner/- appCache 基础知识。

http://www.htmlgoodies.com/html5/other/html-5-appcache-by-example.html- appCache example.

http://www.htmlgoodies.com/html5/other/html-5-appcache-by-example.html- appCache 示例。

http://www.jefclaes.be/2012/04/visualizing-offline-application-cache.html- manifest FALLBACK.

http://www.jefclaes.be/2012/04/visualizing-offline-application-cache.html- 清单回退。

Is swapCache() required in HTML5 offline apps?- swapCache information (read the comments as well).

HTML5 离线应用程序需要 swapCache() 吗?- swapCache 信息(也请阅读评论)。

https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching- general HTTP cache information.

https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching- 一般 HTTP 缓存信息。