search
HomeWeb Front-endJS TutorialHTML5 web caching and application caching

HTML5 web caching and application caching

Jan 13, 2018 am 11:13 AM
h5html5web

This article mainly introduces HTML5 Web caching and application caching (cookie, session). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Before introducing HTML5 web caching, let’s get to know cookies and sessions:

session:

Because HTTP is Status, who are you? What did you do? Sorry, the server doesn't know.

So session appears, which stores user information on the server for future use (such as user name, shopping cart purchases, etc.).

But the session is temporary and will be deleted when the user leaves the website. If you want to store information permanently, you can save it in a database!

Session works: Create a session id (core!!!) for each user. The session id is stored in the cookie, which means that if the browser disables cookies, the session will become invalid! (But it can be implemented in other ways, such as passing session id through URL)

User authentication generally uses session.

Cookie:

Purpose: Data (usually encrypted) stored locally on the client side by the website to mark the user's identity.

  1. When a user visits a webpage, the name is recorded in the cookie;

  2. The next time the user continues to visit the webpage, the user can be read from the cookie Access to records.

The cookie will be carried (even if not needed) in the http request from the same origin, that is, passed back and forth between the client and the server!

The data size of the cookie does not exceed 4k

Validity period of cookie: The set cookie is valid until the expiration time, even if the browser is closed!

localStorage & sessionStorage:

In the early days, cookies were commonly used for local cache, but web storage needs to be safer and faster!

These data will not be saved on the server (stored on the client) and will not affect server performance!

sessionStorage and localStorage data storage also have size limits, but they are much larger than cookies and can reach 5M or even larger!

localStorage: Data storage without time limit!

sessionStorage: As you can see from the English meaning, it is the data storage of the session, so after the user closes the browser (tab/window), the data is deleted!

HTML5 web storage support:

IE8 or above, modern browser.

Data is stored in key-value pairs:

localStorage and sessionStorage have the following methods:

  1. ##localStorage.setItem(key, value): Set (save) data; equivalent to localStorage.key=value!

  2. localStorage.getItem(key): Get data

  3. localStorage.removeItem (key): Delete a single data

  4. localStorage.clear(): Delete all data

  5. localStorage.key(index): Get a certain Index key value


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>web storage</title>
</head>

<body>
    <p id="test"></p>
    <script>
        if (typeof (Storage) != undefined) {
            localStorage.name = &#39;xiao ming&#39;;
            localStorage.setItem(&#39;name1&#39;, &#39;Apple&#39;);
            document.getElementById(&#39;test&#39;).innerHTML = "you are: " + localStorage.name;
            console.log("first:" + localStorage.name1 + "," + localStorage.key(0));
            localStorage.removeItem(&#39;name1&#39;);
            console.log("second: " + localStorage.name1);
            console.log("third: " + localStorage.getItem(&#39;name&#39;));
            localStorage.clear();
            console.log("last:" + localStorage.name);
        } else {
            document.getElementById(&#39;test&#39;).innerHTML = "更新浏览器吧!目前浏览器不支持stroage";
        }
        
    </script>
</body>
</html>

Program running result:

Note: key value pair It is saved as a string, and the type should be changed according to requirements (for example, when adding, it becomes Number type).

HTML5 Application Cache:

By creating a cache manifest file, web applications can be cached and can be accessed without network status!

Application Cache advantages:

1. Offline browsing;

2. Faster speed: cached resources are loaded faster;
3. Reduce browsing Server load: The client will only download or update changed resources from the server

Support:

IE10 or above, modern browsers.

Usage:


<!DOCTYPE html>
<html manifest="demo.appcache">
</html>

Note: To enable the application cache, you need to specify the manifest attribute (extension: .appcache); if the manifest attribute is not specified, the page It will not be cached (unless the page is directly specified in the manifest file!)

The manifest file must be correctly configured on the server with MIME-type: text/cache-manifest.

Manifest file:

The manifest is a simple text file that tells the browser what is cached and what is not cached!

The manifest can be divided into three parts:

CACHE MANIFEST: The files listed in this item will be cached after the first download!

NETWORK: The files listed in this item require a network connection with the server and will not be cached!

FALLBACK: This item lists the fallback page when the page cannot be accessed (such as: 404 page)!

test.appcache:


CACHE MANIFEST
#2017 11 21 v10.0.1
/test.css
/logo.gif
/main.js

NETWORK
/login.php
/register.php

FALLBACK
#/html/目录中文件无法访问时,用/offline.html替代
/html/ /offline.html

Update application cache: 1. The user clears the browser cache!
2. The manifest file is changed (#: indicates a comment, and if it is changed to #2018 1 1 v20.0.0, the browser will re-cache!)
3. The program updates the application cache!

Web Workers:

Web workers are javascript running in the background, independent of other scripts and will not affect page performance!

When executing a script on a general HTML page, the page will not respond unless the script is loaded!

支持情况:IE10以上,现代浏览器

示例:html文件:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>web worker</title>
</head>
<body>
    <p>计数:<output id="count"></output></p>
    <button onclick="startWorker()">开始</button>
    <button onclick="overWorker()">结束</button>

    <script>
        var w;
        function startWorker(){
            // 检测浏览器是否支持web worker
            if(typeof(Worker)!==&#39;undefined&#39;){
                if(typeof(w)==&#39;undefined&#39;){
                    //创建web worker对象
                    w=new Worker(&#39;testWorker.js&#39;);
                }
                // 事件持续监听(即使外部脚本已经完成),除非被终止
                w.onmessage=function(event){
                    document.getElementById(&#39;count&#39;).innerHTML=event.data;
                };
            }else{
                document.getElementById(&#39;count&#39;).innerHTML=&#39;浏览器不支持web worker&#39;;
            }
        }
        function overWorker() {
            // 终止web worker对象,释放浏览器/计算机资源
            w.terminate();
            w=undefined;
        }
    </script>
</body>
</html>

testWorker.js文件:


var i=0;
function timedCount() {
    i+=1;
    // 重要的部分,向html页面传回一段信息
    postMessage(i);
    setTimeout(&#39;timedCount()&#39;,500);
}
timedCount();

注意1:通常web worker不是用于如此简单的任务,而是用在更耗CPU资源的任务!

注意2:在chrome中运行会产生“cannot be accessed from origin 'null'”的错误,我的解决方法是:xampp中开启apache,用http://localhost/进行访问。

web worker缺点:

由于web worker位于外部文件中,所以它无法访问下列javascript对象:

  1. window对象;

  2. document对象;

  3. parent对象。

HTML5 server-sent events(服务器发送事件):

server-sent事件是单向信息传递;网页可以自动获取来自服务器的更新!

以前:网页先询问是否有可用的更新,服务器发送数据,进行更新(双向数据传递)!

支持情况:除IE以外的现代浏览器均支持!

示例代码:html文件:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>sever sent event</title>
</head>
<body>
    <p>sever sent event informations</p>
    <p id="test"></p>
    <script>
        // 判断浏览器是否支持EventSource
        if(typeof(EventSource)!==undefined){
            // 创建EventSource对象
            var source=new EventSource("test.php");
            // 事件监听
            source.onmessage=function(event){
                document.getElementById(&#39;test&#39;).innerHTML+=event.data+"<br>";
            };
        }else{
            document.getElementById(&#39;test&#39;).innerHTML="sorry,浏览器不支持server sent event";
        }
    </script>
</body>
</html>

test.php:


<?php
header(&#39;Content-Type:text/event-stream&#39;);
header(&#39;Cache-Control:no-cache&#39;);

$time=date(&#39;r&#39;);
echo "data:The server time is: {$time} \n\n";
// 刷新输出数据
flush();

注意:后面没有内容,php文件可以不用"?>"关闭!

HTML5 WebSocket:

  1. WebSocket是HTML5提供的一种在单个TCP连接上建立全双工(类似电话)通讯的协议;

  2. 浏览器和服务器之间只需要进行一次握手的操作,浏览器和服务器之间就形成了一条快速通道,两者之间就可直接进行数据传送;

  3. 浏览器通过javascript建立WebSocket连接请求,通过send()向服务器发送数据,onmessage()接收服务器返回的数据。

 WebSocket如何兼容低浏览器:

  1. Adobe Flash Socket;

  2. ActiveX HTMLFile(IE);

  3. 基于multipart编码发送XHR;

  4. 基于长轮询的XHR

WebSocket可以用在多个标签页之间的通信!

相关推荐:

Nginx的Web缓存服务与新浪网的开源NCACHE模块

Web缓存杂谈_html/css_WEB-ITnose

基于反向代理的Web缓存加速可缓存的CMS系统设计_PHP

The above is the detailed content of HTML5 web caching and application caching. 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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor