search
HomeWeb Front-endH5 TutorialDetailed graphic and text explanation of html5 application caching and Web Workers


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 id="This-nbsp-is-nbsp-my-nbsp-HTML-nbsp-page">This is my HTML page</h1>
  </body></html>

style.css

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

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:

CACHE MANIFEST#version 1.0CACHE:index.htmlcss/style.css
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

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:
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>

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

可选值 匹配常量 描述
0 appCache.UNCACHED 未缓存
1 appCache.IDLE 闲置
2 appCache.CHECKING 检查中
3 appCache.DOWNLOADING 下载中
4 appCache.UPDATEREADY 已更新
5 appCache.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>

这里在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;
    };
};

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

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

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>

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;
    }
}

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

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

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

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!

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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool