Home > Web Front-end > H5 Tutorial > body text

Detailed graphic and text explanation of html5 application caching and Web Workers

黄舟
Release: 2017-03-31 11:44:53
Original
2197 people have browsed it


Introduced in html5 Applicationcaching, which means that web applications can be cached and accessed when there is no network connection

Advantages of application caching

  • Offline browsing, users can browse loaded and cached data while offline

  • Speed ​​up loading speed. #Reduce server load

  • ##Implement caching

    If you enable application caching, you need to include the manifest attribute in the
tag. The recommended extension of the manifest file is: ".appcache"

manifest file

The manifest file provides us with three caching methods: version n.n: version indicates the version of the current manifest. , when the version changes, when the user loads again, all files listed under the CACHE label will be downloaded again

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

- NETWORK: Files listed under this heading require a link to the server and will not be cached.

- F

ALL
BACK: The files listed under this title specify the resources to be accessed after the access cache fails. The first one is the access source, and the second one is the replacement file *.html /offline.html. For example
404 page
.
Cached applicationHere I create a web project and create a new html file: index.html

<!DOCTYPE html><html manifest="index.appcache">
  <head>
    <title>index.html</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
  </head> 
  <body>
    <h1>This is my HTML page</h1>
  </body></html>
Copy after login

style.css

@CHARSET "UTF-8";h1 {    color: aqua;}
Copy after login

As you can see here, my page is very simple, and
references

a style.css style file. And in the

tag, the cache file index.appcache is specified. The content of

index.appcache is as follows:

As you can see, here we use the CACHE type cache , indicating that the two files index.html and css/style.css need to be cached. At this time, open the server and browse the web page. After closing the server, you will find that the web page can also be accessed. At this time, press F12, open the developer options, and you will find the following cache:

At the same time, you can also use the NETWORK type cache to indicate which files need to be downloaded online. Here I write the css/style.css file into the NETWORK type cache.

CACHE MANIFEST#version 1.0CACHE:index.htmlNETWORK:css/style.css
Copy after login

First you need to manually clear the previously cached records. Then open the server and browse http://localhost:8080/html5cache/index.html. The display effect is as follows: Detailed graphic and text explanation of html5 application caching and Web Workers

You can see that only the html page is cached at this time, and the css/ is not cached. style.css file, close the server at this time, refresh the page again, the effect is as follows:


You can see that at this time, only the html page is loaded, and no css file is loaded, so the h1 tag The font is the default. Detailed graphic and text explanation of html5 application caching and Web Workers

UpdateDetailed graphic and text explanation of html5 application caching and Web WorkersCache

If you need to update the cache, for example, here I changed the text in the html, and when I visit localhost:8080/html5cache/index.html again , the latest page text will not be loaded. This is because the browser will search in the cache by default. If it is in the cache, it will be taken directly from the cache. Therefore, we need to update the version in the cache file "index.appcache". Yes, as follows:

CACHE MANIFEST#version 1.1CACHE:css/style.cssindex.htmlNETWORK:FALLBACK:
Copy after login
Here, I changed the version to 1.1. When I visit the page again, I will go to the service to download the latest page. At this point, the shortcomings of caching come out. Even if I only update one line of text on a page, when I change the version value in the "index.appcache" file, all the content defined in the CACHE will be downloaded again.

Use js to automatically update the cache

In addition, we can also use the applicationcache

object

to automatically update the cache. As follows:

<script type="text/javascript">
         //添加页面加载函数
        window.addEventListener(&#39;load&#39;, function(e) {

          //为applicationCache对象添加updateready事件 
          window.applicationCache.addEventListener(&#39;updateready&#39;, function(e) {
            //表示manifest中列举的文件已经重新下载并更新成功
            if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {              
            //使用swapCache()方法更新到应用程序中
              window.applicationCache.swapCache();              
              if (confirm(&#39;A new version of this site is available. Load it?&#39;)) {                
              //重新加载当前页面
                window.location.reload();

              }

            } else {                //manifest文件没有变化
                console.log("manifest 没有改变");
            }

          }, false);

        }, false);    </script>
Copy after login

applicationcache is a direct sub-object of the

window object. The event list of this object is as follows:

status returns the cached state
Detailed graphic and text explanation of html5 application caching and Web Workers

可选值匹配常量描述
0appCache.UNCACHED未缓存
1appCache.IDLE闲置
2appCache.CHECKING检查中
3appCache.DOWNLOADING下载中
4appCache.UPDATEREADY已更新
5appCache.OBSOLETE失效

方法

方法名匹配常量
update()发起应用程序缓存下载进程
abort()取消正在进行的缓存下载
swapcache()切换成本地最新的缓存环境

web workers

web workers是运行在后台的脚本,独立于其他的脚本,不会影响页面的性能。类似于android开发中的handler。将繁重耗时的计算放到web worker中来实现,然后将处理的结果返回给主UI线程来显示。

web workers方法

  • postMessage() :用于向html页面回传一段消息。

  • terminate() :终止web workers,并且释放计算机资源。

web workers简单实现

下面使用web workers简单实现一数字更新的demo:
新建一个web工程,创建index.html

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="index.js"></script></head><body>
    <p id="nump">0</p></body></html>
Copy after login

这里在index.html文件当中引入了index.js文件。
index.js

var nump;
window.onload = function(){
    nump = document.getElementById("nump");    var work = new Worker("count.js");
    work.onmessage = function(e) {
        //alert(e.data);
        nump.innerHTML = e.data;
    };
};
Copy after login

可以看到,这里讲更新数据的具体操作,使用Worker来更新,在worker当中加载了count.js文件来做一些耗时,复杂的计算。然后使用worker的onmessage回调方法,将count.js返回的结果重新显示给nump。
count.js

var countNum = 0;function count(){
    postMessage(countNum);//通过postMessage方法将计算结果回传给调用者
    countNum++;
    setTimeout(count,1000);
}
count();
Copy after login

count.js文件比较简单,每隔一秒更新countNum的值,然后回传给调用者,也就是这里的index.js

此时运行效果如下:
Detailed graphic and text explanation of html5 application caching and Web Workers

下面添加一个开始停止的控制按钮

 <button id="start">start</button>
 <button id="stop">stop</button>
Copy after login

index.js

var nump;var work;
window.onload = function(){
    nump = document.getElementById("nump");    
    var start = document.getElementById("start");    
    var stop = document.getElementById("stop");
    start.onclick = startWorker;
    stop.onclick = stopWorker;

};function startWorker() {
    if (work) { //如果work存在,则直接返回
        return;
    } else {
        work = new Worker("count.js");
        work.onmessage = function(e) {
            nump.innerHTML = e.data;
        };
    }
}function stopWorker() {
    if (work) {//如果worker存在,则终止并且为其重新赋值
        work.terminate();
        work = null;
    }
}
Copy after login

此时运行效果如下:
Detailed graphic and text explanation of html5 application caching and Web Workers

另外我们还可以通过navaigator对象的onLine属性来判断当前浏览器是否在线,该属性属于只读属性,会返回boolean类型的值。

if(window.navigator.onLine) {    //在线} else {    //离线}
Copy after login

The above is the detailed content of Detailed graphic and text explanation of html5 application caching and Web Workers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template