Home  >  Article  >  Web Front-end  >  HTML5 offline storage principle and implementation code examples

HTML5 offline storage principle and implementation code examples

黄舟
黄舟Original
2017-03-09 15:49:062279browse

Preface

Using HTML5, you can easily create an offline version of a web application by creating a cache manifest file.

HTML5 introduces application caching, which means web applications can be cached and accessed when there is no Internet connection. App cache brings three benefits to apps:

  • Offline browsing – users can use apps while they are offline

  • Speed ​​– Cached Resources load faster

  • Reduce server load – the browser will only download updated or changed resources from the server.

Principle and environment

As mentioned above, the offline storage of HTML5 is based on a newly created .appcache file, through The Parsing List on this file stores resources offline, and these resources will be stored like cookies. Later, when the network is offline, the browser will display the page through the data stored offline.

Just like cookies, offline storage of html5 also requires a server environment.
Here is a small tool - a simple iis server. Place it in the project update directory and double-click to run it to simulate the server environment.
Link: http://pan.baidu.com/s/1jG86UV0 Password: ja9h

Analysis list

Before you start, you need to understand manifest (i.e. .appcache file), how to write the above parsing list.

Manifest files are simple text files that tell the browser what is cached (and what is not cached).

Manifest files can be divided into three sections:

  • CACHE MANIFEST - Files listed under this heading will be cached after the first download

  • NETWORK - The files listed under this heading require a connection to the server and will not be cached

  • ##FALLBACK - The files listed under this heading require a connection to the page Fallback page when inaccessible (such as 404 page)

When online, the user agent will read the manifest every time it visits the page. If it finds that it has changed, it will reload it. All resources in the manifest

CACHE MANIFEST

The first line, CACHE MANIFEST, is required:

CACHE MANIFEST
/theme.css
/logo.gif
/main.js

The manifest file above lists three resources : A CSS file, a GIF image, and a JavaScript file. When the manifest file loads, the browser downloads these three files from the root directory of the website. Then, whenever the user disconnects from the Internet, these resources are still available.

NETWORK

#Whitelist, use the wildcard "*". It will enter the open state of the whitelist. In this state, all URLs that do not appear in the relevant Cache area will be used by default HTTP related cache header policy.

The following NETWORK section stipulates that the file "login.asp" will never be cached and is not available offline:

NETWORK:
login.asp

You can use Star number to indicate that all other resources/files require an Internet connection:

NETWORK:
login.asp

FALLBACK

The FALLBACK subsection below specifies that if an Internet connection cannot be established, "offline.html" is used instead of the /html5/ directory All files in:

ALLBACK:
/html5/ /404.html

Note: The first URI is the resource, the second is the fallback.

Update cache

Once an app is cached, it remains cached until the following occurs:

  • The user clears the browser cache

  • The manifest file is modified

  • The application cache is updated by the program

Demo

case/
  |-- index.html
  |
  |-- demo.appcache
  |
  |-- 简易IIS服务器.exe
  |
  `-- image
        |-- HTML5 offline storage principle and implementation code examples
        `-- HTML5 offline storage principle and implementation code examples

index.html

<!DOCTYPE html>
<html lang="en" manifest="demo.appcache">
<head>
    <meta charset="UTF-8">
    <title>HTML5离线存储</title>
</head>
<body>
    <img src="image/HTML5 offline storage principle and implementation code examples" alt="">
    <img src="image/HTML5 offline storage principle and implementation code examples" alt="">
</body>
</html>

demo.appcache

CACHE MANIFEST
#v01
image/HTML5 offline storage principle and implementation code examples

NETWORK:
*

FALLBACK:
/

image folder stores

HTML5 offline storage principle and implementation code examples

HTML5 offline storage principle and implementation code examples

HTML5 offline storage principle and implementation code examples

HTML5 offline storage principle and implementation code examples

Okay, then execute

Simple IIS Server.exe and give it a try.

When iis is turned on

Alt text

When iis is turned off (it is turned off, pausing will not see the effect)

Alt text

You can see that

Picture 1 has been successfully displayed offline, but Picture 2 cannot be displayed as normal.

Now I want to change the positions of

Picture 2 and Picture 1.

Replace the Html part

<body>
    <img src="image/HTML5 offline storage principle and implementation code examples" alt="">
    <img src="image/HTML5 offline storage principle and implementation code examples" alt="">
</body>

At this time, I found a problem. The html was obviously modified, so why the pictures were not replaced. Didn’t I write an asterisk in

NETWORK of the demo.appcache file? In addition to CACHE MANIFEST files and other files are in online mode. According to the information, the page that introduces the manifest will still be cached by the user agent even if it is not included in the cache list.

Okay, then I will update the

.appcache file, so I will change the version number in the header to #v02. Refreshed the page and still no response! Refresh again, there it is! Why?

对于浏览器来说,manifest的加载是要晚于其他资源的. 这就导致check manifest的过程是滞后的.发现manifest改变.所有浏览器的实现都是紧随这做静默更新资源.以保证下次pv,应用到更新.

通过控制台我们能够窥探一二:

  • 第一次刷新,应用程序缓存更新准备事件,
    Alt text

  • 第二次刷新才会看到效果。
    Alt text

缓存立即执行

我们的产品已经更新了用户却要第二次进来才能够看到,这样用户体验也太差了吧,有什么方式能够解决呢?好在html5给javascript提供了相关的API。

API篇幅太多自行查看把,这里我晒下我测试成功的code:

 /*code1,简单粗暴的*/
    applicationCache.onupdateready = function(){
        applicationCache.swapCache();
        location.reload();
    };
    /*code2,缓存公用方法*/
    // var EventUtil = {
    //     addHandler: function(element, type, handler) {
    //         if (element.addEventListener) {
    //             element.addEventListener(type, handler, false);
    //         } else if (element.attachEvent) {
    //             element.attachEvent("on" + type, handler);
    //         } else {
    //             element["on" + type] = handler;
    //         }
    //     }
    // };
    // EventUtil.addHandler(applicationCache, "updateready", function() {      //缓存更新并已下载,要在下次进入页面生效
    //     applicationCache.update();  //检查缓存manifest文件是否更新,ps:页面加载默认检查一次。
    //     applicationCache.swapCache();  //交换到新的缓存项中,交换了要下次进入页面才生效
    //     location.reload();              //重新载入页面
    // });

code1一般用在页面加载时直接触发,而code2的方式可后期检查更新。

注意事项

  • 站点离线存储的容量限制是5M

  • 如果manifest文件,或者内部列举的某一个文件不能正常下载,整个更新过程将视为失败,浏览器继续全部使用老的缓存

  • 引用manifest的html必须与manifest文件同源,在同一个域下

  • 在manifest中使用的相对路径,相对参照物为manifest文件

  • CACHE MANIFEST字符串应在第一行,且必不可少

  • 系统会自动缓存引用清单文件的 HTML 文件

  • manifest文件中CACHE则与NETWORK,FALLBACK的位置顺序没有关系,如果是隐式声明需要在最前面

  • FALLBACK中的资源必须和manifest文件同源

  • 当一个资源被缓存后,该浏览器直接请求这个绝对路径也会访问缓存中的资源。

  • 站点中的其他页面即使没有设置manifest属性,请求的资源如果在缓存中也从缓存中访问

  • 当manifest文件发生改变时,资源请求本身也会触发更新

The above is the detailed content of HTML5 offline storage principle and implementation code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn